public class Primes1 { public static boolean[] sieveOfE ( int N ) { boolean[] isPrime = new boolean[ N + 1 ]; int i, j, k; /* ------------------------ Initialize isPrime[] ------------------------ */ isPrime[0] = false; isPrime[1] = false; for ( i = 2; i <= N; i++ ) isPrime[i] = true; // They are all candidates /* ------------------------ Perform the sieve of E ------------------------ */ k = 2; // Start with 2 to find all primes while ( k <= N ) { /* ---------------------------------------- Find the next prime number ---------------------------------------- */ 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; /* ======================================= Set up k to start the next iteration ======================================= */ k = i+1; } return isPrime; } public static void main(String[] args) { boolean[] result; int i; result = sieveOfE ( 120 ); for ( i = 0 ; i < result.length ; i++ ) { if ( result[i] ) System.out.print( i + " "); } System.out.println( ); } }