Our text discusses an Object-Oriented approach to finding prime numbers by means of the sieve of Eratosthenes. It's given in C++ in the text. Here's the equivalent program in Java. The program doesn't have any comments for documentation. We'll discuss it in class, and you can see the text for details.
public class SieveDemo { public static void main (String [] args) { int colcounter=0; Counter c = new Counter(2); // initialize the Counter c at 2 Sieve s = new Sieve(c); // initialize the Sieve s's source to c int next; do { next = s.out(); // get the next prime System.out.format("%5d ", next); // and print it if ((++colcounter)%10==0) System.out.println(); } while (next < 10000); System.out.println(); } }
public class Item { protected Item source; public Item () {} public Item (Item sourceIn) { source = sourceIn; } public int out() { return 0; } }
public class Filter extends Item { private int factor; public Filter (Item sourceIn, int factorIn) { source = sourceIn; factor = factorIn; } public int out() { int n; do n = source.out(); while (n % factor == 0); return n; } }
public class Counter extends Item { private int value; public Counter (int valueIn) { value = valueIn; } public int out() { return value++; } }
public class Sieve extends Item { private int value; public Sieve (Item sourceIn) { source = sourceIn; } public int out() { int n = source.out(); source = new Filter(source,n); return n; } }
Here's the beginning of a run of the program:
$ java SieveDemo 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71The list it produces continues on for some time. The whole list of Prime Numbers to 10000 can be found at http://aleph0.clarku.edu/~djoyce/numbers/primes.html
Back to the course page.