Programming 2 with Java

Exercise: Prime Counter with Streams

  1. Define an integer predicate isPrime that indicates for an integer whether it is a prime number.
  2. Implement a program that uses the predicate as a filter of an IntStream to count the prime numbers in a given range, and measure the time taken.
    > java PrimeCounter 1 10000000
    664579 prime numbers found in 4.859 seconds
    
    (The table on the Wikipedia page of the prime-counting function can be used to verify the results.)
  3. First use a sequential stream and then a parallel stream, and compare the time taken.

Solution