Skip to content

Commit c7afd55

Browse files
WIP original
1 parent dd4fab3 commit c7afd55

File tree

1 file changed

+31
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)