import element.*; public class Sieve { public static void initialize(boolean prime[]) // pre: prime is an array of booleans // post: all entries in prime are optimistically set to true { int n; // initialize the array (entries 0,1 unused) for (n = 2; n < prime.length; n++) { prime[n] = true; } } public static void crossOut(int n, boolean prime[]) // pre: n < prime.length // post: all nontrivial multiples (m) of n are identified as composite { int m; for (m = 2*n; m < prime.length; m += n) { prime[m] = false; } } public static void print(ConsoleWindow c, boolean prime[]) // pre: c is non-null, prime is a computed sieve // post: the indices of the true entries of prime are printed on c { int n; // print out primes: uncrossed numbers for (n = 2; n < prime.length; n++) { if (prime[n]) { c.out.print(n+" "); } } c.out.println(); } public static void main(String args[]) // post: compute the primes between 2 and max, inclusive { ConsoleWindow c = new ConsoleWindow(); final int max = 100; boolean prime[] = new boolean[max+1]; int n; // assume all values are potentially prime initialize(prime); // cross out multiples of uncrossed numbers for (n = 2; n <= max; n++) { if (prime[n]) // needn't cross out multiples of composites { crossOut(n,prime); } } // print out indices of entries that remain "prime" print(c,prime); } } /* 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 */