Generating random BigIntegers
suggest changeThe BigInteger class has a constructor for generating random BigIntegers, given a java.util.Random and an int that specifies the maximum number of bits. Calling BigInteger(int, Random) like this:
BigInteger randomBigInt = new BigInteger(bitCount, sourceOfRandomness);
returns a non-negative BigInteger uniformly distributed from 0 (inclusive) to 2bitCount (exclusive), assuming sourceOfRandomness is a fair bit source. A negative bitCount throws IllegalArgumentException.
new BigInteger(2147483647, sourceOfRandomness) asks for a value with up to Integer.MAX_VALUE bits. It does not produce every positive BigInteger: magnitudes outside the supported range are rejected, and the byte allocation can fail.
You choose sourceOfRandomness. A new Random() is good enough in most cases:
new BigInteger(32, new Random());
If you’re willing to give up speed for higher-quality random numbers, you can use a new SecureRandom() instead:
import java.security.SecureRandom;
// somewhere in the code...
new BigInteger(32, new SecureRandom());
You can even implement an algorithm on the fly with an anonymous class. Rolling out your own RNG algorithm will leave you with low-quality randomness, so use an algorithm that is known to be decent unless you want the resulting BigInteger to be predictable. This override also ignores bits. Random.next(int) must return a value whose low bits bits are the random ones, so this does not meet that contract:
new BigInteger(32, new Random() {
int seed = 0;
@Override
protected int next(int bits) {
seed = ((22695477 * seed) + 1) & 2147483647; // Values shamelessly stolen from Wikipedia
return seed;
}
});