If your numbers can be out of the int range, then you should use long
, or failing in that, BigInteger
.
Use the information in this question to create a random BigInteger
, and if it is even simply add 1 to it.
BigInteger randomOdd(BigInteger min, BigInteger max) {
BigInteger range = max.subtract(min);
// expected iterations: 2 - max iterations: infinite
BigInteger tmp;
do {
tmp = new BigInteger(n.bitLength(), rng); // rng is your Random Number Generator
} while (tmp.compareTo(range) >= 0);
BigInteger result = min.add(tmp);
// force the result to be odd
// TODO: will this push it over max?
result = result.or(BigInteger.ONE);
return result;
}
Alternatively, you could use a method on the BigInteger class: BigInteger.probablePrime()
:
public static BigInteger probablePrime(int bitLength,
Random rnd)
Returns a positive BigInteger
that is probably prime, with the specified bitLength
. The probability that a BigInteger returned by this method is composite does not exceed 2^100
.
Parameters:
- bitLength - bitLength of the returned
BigInteger
.
- rnd - source of random bits used to select candidates to be tested for primality.
Returns:
- a
BigInteger
of bitLength bits that is probably prime
If it's probably prime, it's also probably odd.