The Java Program: Sieve.java

  1 // Sieve.java -- Sieve of Eratosthenes using streams represented as classes
  2 
  3 // an "Emitter" produces an integer
  4 abstract class Emitter {
  5    abstract int out ();
  6 }
  7 
  8 // ignore the source and just count from the initial value
  9 class Counter extends Emitter {
 10    private int value;
 11    Counter (int v) { value = v; }
 12    int out () { return (value++); }  // post increment!
 13 }
 14 
 15 // filter all multiples of "factor" from the "source"
 16 class Filter extends Emitter {
 17    private final int factor;
 18    private final Emitter source;
 19    Filter (Emitter src, int f) { source = src; factor = f; }
 20    int out () {
 21       while (true) {
 22          final int n = source.out();
 23          if (n%factor!=0) return (n);
 24       }
 25    }
 26 }
 27 
 28 public class Sieve {
 29 
 30    public static void main (String args[])  {
 31       final int max  = args.length>0?Integer.parseInt(args[0]):100;
 32       Emitter p = new Counter (2);  // initialize source to 2,3,4,5,6,...
 33       while (true) {
 34          final int next = p.out();  // take the first in the stream,
 35          p = new Filter (p, next);  // but filter all multiples in future
 36          if (next>max) break;
 37          System.out.println (next + " is prime.");
 38       }
 39    }
 40 
 41 }