The answer to jprete is excellent if your max / min ratio is not close to 1.
If you have a limited range, it is best to do something like the following:
// this is pseudocode: // // round min down to multiple of 6, max up to multiple of 6 min6 = floor(min/6); max6 = ceil(max/6); maybePrimeModuli = [1,5]; do { b = generateRandom(maybePrimeModuli.length); // generate a random offset modulo 6 which could be prime x = 6*(min6 + generateRandom(max6-min6)) + b; // generate a random number which is congruent to b modulo 6 // from 6*min6 to 6*max6-1 // (of the form 6k+1 or 6k+5) // the other choices 6k, 6k+2, 6k+3, 6k+4 are composite } while not isProbablePrime(x);
the prime density is pretty high overall, it's basically 1 in log (x), so you don't have to repeat too many times to find a prime. (As an example: for numbers around 10 23, each of 52 integers on average is a prime number. The above code only bothers 2 out of every 6 numbers, so you end up looping an average of 17 times for numbers around 10 23. )
Just make sure you have a good conformance test, and Java BigInteger is one.
As an exercise for the reader, extend the function above to filter out more complex numbers in advance using 30k + x (modulo 30, there are 22 modules that are always composite, only 8 remaining, which can be simple), or 210k + x.
edit: see also US Patent No. 7149763 (OMFG !!!)
Jason s
source share