Programming 2 with Java

Exercise: Prime Counter with Fork/Join Pool

Prime Counter

  1. Implement a recursive class PrimeCounterTask whose constructor takes a minimum and a maximum number and whose compute method
    • checks whether the minimum and maximum numbers are equal and if so, uses the utitlity class Primes.java to check if the number is prime, and returns 0 or 1 accordingly
    • splits the range into two subranges and forks two subtasks each of which computes the number of prime numbers in one subrange
  2. Implement the program PrimeCounter which
    • takes a minimum and a maximum number as command line arguments
    • creates a fork/join pool and submits a task that counts the prime numbers in given range
    • displays the number of found prime numbers and the required runtime
    > 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. Run the program with different number of threads and compare the runtimes.

Solution