patternjavaMinor
Find the next prime number — flow control of nested `for` loops
Viewed 0 times
numbertheflowcontrolloopsnextnestedforfindprime
Problem
This code works perfectly, but it bothers me. Having a labeled, nested
From the names I am using, this should be fairly self-documenting, but to say it in English: This is part of a
All it does is find the next prime that has not already been found, memoize it, and return it.
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 primeList = new ArrayList(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.
Solution
Factor out the inner loop into a method (not just for the sake of structure, but because it is a method
Then
bool is_next_prime(int testNum)):for (...) {
if (testNum % prime) == 0)
return false;
}
return true;Then
int getNextPrime() {
int testNum = primeList.get(primeList.size() - 1) + 2;
while (!is_next_prime(testNum)) {
testNum += 2;
}
return testNum;
}Code Snippets
for (...) {
if (testNum % prime) == 0)
return false;
}
return true;int getNextPrime() {
int testNum = primeList.get(primeList.size() - 1) + 2;
while (!is_next_prime(testNum)) {
testNum += 2;
}
return testNum;
}Context
StackExchange Code Review Q#107839, answer score: 5
Revisions (0)
No revisions yet.