/** lazy version, but inefficient when called multiple times and not really quicker than Sieve1 anyway (can you see why?) so probably Sieve1 should be the preferred version */ import java.util.*; public class Sieve2 { private BitSet primes; public Sieve2(int n) { primes = new BitSet(n); for(int i = 1; i < n; i++) primes.set(i); } public Enumeration elements() { return new SieveEnumeration(); } public class SieveEnumeration implements Enumeration { private int index = 1; public boolean hasMoreElements() { int n = primes.size(); for(int i = index+1; i < n; i++) if (primes.get(i)) { if (i*i < n) for(int j = 2*i; j < n; j += i) primes.clear(j); index = i; return true; } return false; } public Object nextElement() { return new Integer(index);} } public static void main(String[] args) { Sieve2 p = new Sieve2(Integer.parseInt(args[0])); Enumeration primes = p.elements(); 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."); } }