I am trying to parallelize a prime number counter as an exercise. I have refactored the original code and separated the long loops from others so that I can parallelize them. Now I have the following code and multithreading is looking difficult as I need to keep track of the primes found (in order) and count the number of primes found.
nthPrime(long n) gets the number of primes to search for. returns the nth prime. count is an ArryList
public static long nthPrime(long n) {
count.add((long) 1);
if (n < 2) {
count.add((long) 3);
return getCount();
}
count.add((long) 3);
if (n == 2) {
return getCount();
}
step = 4;
candidate = 5;
checker(n, step, candidate);
return getCount();
}
private static long checker(long n, int step, long candidate) {
while (count.size() < n) {
if (Checker.isPrime(candidate)) {
// checks the number for possible prime
count.add(candidate);
}
step = 6 - step;
candidate += step;
}
return getCount();
}
Any ideas on using util.concurrent or threading to parallelize this?
Thanks