blob: beb0b3ad85c7eda47f21d86df75674fed06b4aee (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
val sieve = { int N ->
// The main Sieve array
bool[] !ary = new bool[N];
// The primes less than N
u32[] !primes = new u32[N>>1];
// Number of primes so far, searching at index p
int nprimes = 0, p=2;
// Find primes while p^2 < N
while( p*p < N ) {
// skip marked non-primes
while( ary[p] ) p++;
// p is now a prime
primes[nprimes++] = p;
// Mark out the rest non-primes
for( int i = p + p; i < ary#; i+= p )
ary[i] = true;
p++;
}
// Now just collect the remaining primes, no more marking
for( ; p < N; p++ )
if( !ary[p] )
primes[nprimes++] = p;
// Copy/shrink the result array
u32[] !rez = new u32[nprimes];
for( int j=0; j < nprimes; j++ )
rez[j] = primes[j];
return rez;
};
|