001package edu.pdx.cs410J.java8;
002
003import java.util.stream.IntStream;
004
005/**
006 * Demonstrates the use of parallel streams by printing the prime numbers that
007 * are less than a given integer.
008 */
009public class ComputePrimeNumbers {
010
011  public static void main(String[] args) {
012    int maximumValue = Integer.parseInt(args[0]);
013
014    long serialDuration = timeOperation(
015      () -> computePrimeNumbers(IntStream.rangeClosed(0, maximumValue)));
016    long parallelDuration = timeOperation(
017      () -> computePrimeNumbers(IntStream.rangeClosed(0, maximumValue).parallel()));
018
019    System.out.println(String.format("Printed primes less than %d (serial)   in %d nanoseconds", maximumValue, serialDuration));
020    System.out.println(String.format("Printed primes less than %d (parallel) in %d nanoseconds", maximumValue, parallelDuration));
021  }
022
023  private static void computePrimeNumbers(IntStream stream) {
024    long count = stream.filter(ComputePrimeNumbers::isPrime)
025      .count();
026    System.out.println("Computed " + count + " primes");
027  }
028
029  private static long timeOperation(Runnable operation) {
030    long start = System.nanoTime();
031
032    operation.run();
033
034    return System.nanoTime() - start;
035  }
036
037  /**
038   * See http://en.wikipedia.org/wiki/Primality_test
039   */
040  private static boolean isPrime(int n) {
041    if (n <= 3) {
042      return n > 1;
043
044    } else if (n % 2 == 0 || n % 3 == 0) {
045      return false;
046
047    } else {
048      for (int i = 5; i * i <= n; i += 6) {
049        if (n % i == 0 || n % (i + 2) == 0) {
050          return false;
051        }
052      }
053      return true;
054    }
055  }
056}