import java.util.Arrays; public class Primes { public static long odd_sieve(int n) { boolean[] primes = new boolean[(n >> 1) - 1]; int i, j, step; short[][] wheel = { { 1,2,1,2,3,1,3,2,1,2,3,3,1,3,2,1,3,2,3,4,2,1,2,1,2,4,3,2,3,1,2,3,1,3,3,2,1,2,3,1,3,2,1,2,1,5,1,5 }, { 2,4,2,4,6,2,6,4,2,4,6,6,2,6,4,2,6,4,6,8,4,2,4,2,4,8,6,4,6,2,4,6,2,6,6,4,2,4,6,2,6,4,2,4,2,10,2,10 }, { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,0 } }; short wi = 0; i = 59; step = 11; j = 4; wi = 0; do { if (!primes[j]) { i = (step * step >> 1) - 1; short ki = wi; while (true) { try { primes[i] = true; i += step * wheel[0][ki]; ki = wheel[2][ki]; } catch (ArrayIndexOutOfBoundsException e) { break; } } } step += wheel[1][wi]; j += wheel[0][wi]; wi = wheel[2][wi]; } while (i <= n); long s = 17; wi = 0; j = 4; while (true) { try { if (!primes[j]) { s += (j << 1) + 3; } j += wheel[0][wi]; wi = wheel[2][wi]; } catch (ArrayIndexOutOfBoundsException e) { return s; } } } public static void main(String[] args) { Primes t = new Primes(); double runtime = 0; long start, stop, end, sum = 0; int tests = 0, maxint = 0; try { tests = Integer.parseInt(args[0]); maxint = Integer.parseInt(args[1]); if (tests < 1 || maxint < 2) { throw new Exception(); } } catch (Exception e) { System.out.println("Usage: java Primes "); System.exit(1); } long[] runtimes = new long[tests]; System.out.printf("Finding the sum of all primes <= %d.\nPerforming %d tests\n", maxint, tests); for (int i = 0; i < tests; ++i) { System.out.print("."); start = System.nanoTime(); sum = odd_sieve(maxint); stop = System.nanoTime(); runtimes[i] = stop - start; //System.out.printf("#%d-> Sum: %d [time=%.2fms]\n", i, sum, runtimes[i]/1000000.0); } double max = runtimes[0]; double min = runtimes[0]; for (long r : runtimes) { if (max < r) { max = r; } else if (min > r) { min = r; } runtime += r; } System.out.printf("\nSum of all primes <= %d: %d\n", maxint, sum); System.out.printf(" * Slowest: %.2fms\t * Average: %.2fms\t * Fastest: %.2fms\n\n", max / 1000000, runtime / (tests * 1000000), min / 1000000); } }