mirror of
https://github.com/vlang/v.git
synced 2025-09-13 14:32:26 +03:00
examples: use a sieve of Eratosthenes in primes.v, to handle bigger inputs more efficiently
This commit is contained in:
parent
75417c55fc
commit
bb13e6601e
1 changed files with 20 additions and 20 deletions
|
@ -1,24 +1,24 @@
|
||||||
fn is_prime(n int) bool {
|
import math { log }
|
||||||
if n <= 1 {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
for i := 2; i * i <= n; i++ {
|
|
||||||
if n % i == 0 {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
fn main() {
|
n := arguments()[1] or { '10' }.int()
|
||||||
how_many := arguments()[1] or { '10' }.int()
|
sz := if n < 15 {
|
||||||
mut count := 0
|
50
|
||||||
mut num := 2
|
} else {
|
||||||
for count < how_many {
|
ln := log(f64(n))
|
||||||
if is_prime(num) {
|
int(f64(n) * (ln + log(ln))) + 1
|
||||||
println(num)
|
|
||||||
count++
|
|
||||||
}
|
}
|
||||||
num++
|
mut sieve := []bool{len: sz}
|
||||||
|
for i := 2; i * i < sz; i++ {
|
||||||
|
if !sieve[i] {
|
||||||
|
for j := i * i; j < sz; j += i {
|
||||||
|
sieve[j] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
mut c := 0
|
||||||
|
for i := 2; c < n && i < sz; i++ {
|
||||||
|
if !sieve[i] {
|
||||||
|
println(i)
|
||||||
|
c++
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue