|
|
![]() |
|
public class PrimeSieve { public static boolean[] sieveOfE( int N ) { .... } } |
boolean[] out = new boolean[ N + 1 ]; /* ------------------------ Initialize out[] ------------------------ */ out[0] = false; out[1] = false; set all other values out[i] = true; // They are all candidates /* ------------------------ Perform the sieve of E ------------------------ */ Find the next value out[i] == true; Set: out[2*i] = false, out[3*i] = false, .... (upto out[N]) Find the next value out[i] == true; Set: out[2*i] = false, out[3*i] = false, .... (upto out[N]) And so on... |
boolean[] out = new boolean[ N + 1 ]; /* ------------------------ Initialize out[] ------------------------ */ out[0] = false; out[1] = false; for ( i = 2; i <= N; i++ ) out[i] = true; // They are all candidates /* ------------------------ Perform the sieve of E ------------------------ */ k = 1; // Start before the first prime number while ( k <= N ) { Starting from k+1, find next prime number i; Set: out[2*i] = false, out[3*i] = false, .... (upto out[N]) k = i; } |
public static boolean[] sieveOfE ( int N )
{
boolean[] isPrime = new boolean[ N + 1 ]; // Return variable
int i, j, k;
/* ------------------------
Initialize isPrime[]
------------------------ */
isPrime[0] = false; // 0 is not prime
isPrime[1] = false; // 1 is not prime
for ( i = 2; i <= N; i++ )
isPrime[i] = true; // All other number are possible candidates
/* ------------------------
Perform the sieve of E
------------------------ */
k = 2; // Start with 2 to find all primes
while ( k <= N )
{
/* ----------------------------------------
Starting from k, find next
prime number number i
A prime number is detected by:
isPrime[i] == true
---------------------------------------- */
for ( i = k; i <= N; i++ )
if ( isPrime[i] )
break; // Found !
/* --------------------------------------
Set: isPrime[2*i] = false,
isPrime[3*i] = false,
....
(upto isPrime[N])
-------------------------------------- */
for ( j = 2*i; j <= N; j = j + i )
isPrime[j] = false;
k = i+1; // Set up k for next iteration !!!
}
return isPrime;
}
|
How to run the program:
|