class primesSeq { // Find all primes between 2 and N final static int PERLINE = 10; public static void main (String args[]) { int N = 100; boolean debug = false; try { N = Integer.parseInt(args[0]); } catch (ArrayIndexOutOfBoundsException e) {} catch (NumberFormatException e) {} try { debug = Boolean.valueOf(args[1]).booleanValue(); } catch (ArrayIndexOutOfBoundsException e) {} if (N < 2) { System.out.println("N < 2"); System.exit(-1); } boolean[] isPrime = new boolean[N+1]; // 1..N rather than 0..N-1 for (int i=0; i<=N; i++) isPrime[i] = true; int crossingOutPrime = 2; int crossingOutSquared = 4; // int finalCross = (int)(Math.floor(Math.sqrt((double)N))); int numPrimes = 0; System.out.println("Find all primes between 2 and " + N); while (crossingOutSquared <= N) { // cross out all multiples of this prime for (int i = crossingOutSquared; i<=N; i=i+crossingOutPrime) { isPrime[i] = false; } while (!isPrime[++crossingOutPrime]) {} // advance to next prime crossingOutSquared = crossingOutPrime*crossingOutPrime; } for (int i=2; i<=N; i++) { if (isPrime[i]) { numPrimes++; if (debug) { System.out.print(" " + i); if ((numPrimes % PERLINE) == 0) System.out.print("\n"); } } } if (debug) if ((numPrimes % PERLINE) != 0) System.out.print("\n"); System.out.println("There are " + numPrimes + " in this range"); } } /* ............... Example compile and run(s) % uname -a SunOS cheshire 5.4 Generic_101945-32 sun4m sparc % $JAVAHOME/bin/javac primesSeq.java % $JAVAHOME/bin/java primesSeq 100 true Find all primes between 2 and 100 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 There are 25 in this range % time $JAVAHOME/bin/java primesSeq 1000 Find all primes between 2 and 1000 There are 168 in this range 0.0u 1.0s 0:02 39% 0+0k 0+0io 0pf+0w % time $JAVAHOME/bin/java primesSeq 10000 Find all primes between 2 and 10000 There are 1229 in this range 1.0u 1.0s 0:02 76% 0+0k 0+0io 0pf+0w % time $JAVAHOME/bin/java primesSeq 100000 Find all primes between 2 and 100000 There are 9592 in this range 3.0u 1.0s 0:05 75% 0+0k 0+0io 0pf+0w % time $JAVAHOME/bin/java primesSeq 1000000 Find all primes between 2 and 1000000 There are 78498 in this range 30.0u 1.0s 0:32 95% 0+0k 0+0io 0pf+0w % time $JAVAHOME/bin/java primesSeq 10000000 Find all primes between 2 and 10000000 There are 664579 in this range 316.0u 2.0s 5:20 99% 0+0k 0+0io 0pf+0w */