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 < 0)
throw new IllegalArgumentException("min must be positive.");
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;
}
isPrime
method as well? \$\endgroup\$Random
may not be good enough). You're vulnerable to integer overflow; depending on the starting values ofmin
/max
(and the implementation ofisPrime()
), you could spin through all negative numbers. There's probably at least one additional optimization for the prime range-check, something about 3 prime numbers every 100 or something (I can't remember exactly what it was, though). \$\endgroup\$Integer.MAX_VALUE
is odd - if it were even, you would be. Other things - the even/odd check can be performed first, before the initial check for primeness of min/max. Movemin += 2;
above the prime check in thewhile (min < max)
loop - you check the 'initial' min value twice. \$\endgroup\$