This code works perfectly, but it bothers me. Having a labeled, nested for
loop, with a true
condition, a break
statement, and a continue label
...it really bothers me. But I couldn't figure out any other way to arrange the flow control here without sacrificing the efficiency. Any ideas?
private static ArrayList<Integer> primeList = new ArrayList<Integer>(Arrays.asList(2,3));
public static int getNextPrime() {
int testNum;
search:
for (testNum = (primeList.get(primeList.size() - 1) + 2); true; testNum += 2) {
int prime = 0;
for (int index = 1; prime * prime <= testNum; index++) {
prime = primeList.get(index);
if (testNum % prime == 0) continue search;
}
break;
}
primeList.add(testNum);
return testNum;
}
From the names I am using, this should be fairly self-documenting, but to say it in English: This is part of a public class Primes
that I wrote, specifically the part that actually does the finding of primes. My various other methods (fillListToIndex
, fillListToValue
, findPrimeN
—not shown) all ultimately rely on getNextPrime()
for the actual primality testing.
All it does is find the next prime that has not already been found, memoize it, and return it.