patternjavaMinor
Random Prime generator
Viewed 0 times
randomprimegenerator
Problem
I have this method that will give a random prime for a given range (min inclusive an max not inclusive) all comments are welcome:
public static int randomPrime(int min, int max) {
if (min = max)
throw new IllegalArgumentException("min must be smaller the max.");
if (!containsPrime(min,max))
throw new IllegalArgumentException("no Primes in this interval.");
if (rand == null) {
rand = new Random();
}
int out = rand.nextInt(max - min) + min;
while (!isPrime(out)) {
out = rand.nextInt(max - min) + min;
}
return out;
}
private static boolean containsPrime(int min, int max) {
if (isPrime(min)||isPrime(max-1)){
return true;
}
if(min%2==0){
min +=1;
}
while (min<max){
if (isPrime(min)){
return true;
}
min +=2;
}
return false;
}Solution
int out = rand.nextInt(max - min) + min;
while (!isPrime(out)) {
out = rand.nextInt(max - min) + min;
}
return out;This duplicate code can be replaced with a do/while loop. The rule of thumb is, if you always need to perform an action at least once, do while!
int out;
do {
out = rand.nextInt(max - min) + min;
} while(!isPrime(out));
return out;Code Snippets
int out = rand.nextInt(max - min) + min;
while (!isPrime(out)) {
out = rand.nextInt(max - min) + min;
}
return out;int out;
do {
out = rand.nextInt(max - min) + min;
} while(!isPrime(out));
return out;Context
StackExchange Code Review Q#19993, answer score: 4
Revisions (0)
No revisions yet.