/******** have an explicit enumerator */ import java.util.*; public class Sieve1 { private BitSet primes; public Sieve1(int n) { primes = new BitSet(n); for(int i = 1; i < n; i++) primes.set(i); for(int i = 2; i*i < n; i++) if (primes.get(i)) for(int j = 2*i; j < n; j += i) primes.clear(j); } public Enumeration elements() { return new SieveEnumeration(); } public class SieveEnumeration implements Enumeration { private int index = 1; public boolean hasMoreElements() { index++; int n = primes.size(); while (! primes.get(index)) if (++index > n) return false; return true; } public Object nextElement() { return new Integer(index);} } public static void main(String[] args) { Sieve1 p = new Sieve1(Integer.parseInt(args[0])); Enumeration primes = p.elements(); while (primes.hasMoreElements()) System.out.println(primes.nextElement()); primes = p.elements(); int count = 0; while ((primes.hasMoreElements()) && (((Integer) primes.nextElement()).intValue() < 42)) count++; System.out.println(count + " of these primes are smaller than 42."); } }