Generating random BigIntegers

suggest change

The BigInteger class has a constructor dedicated to generate random BigIntegers, given an instance of java.util.Random and an int that specifies how many bits will the BigInteger have. Its usage is quite simple - when you call the constructor BigInteger(int, Random) like this:

BigInteger randomBigInt = new BigInteger(bitCount, sourceOfRandomness);

then you’ll end up with a BigInteger whose value is between 0 (inclusive) and 2bitCount (exclusive).

This also means that new BigInteger(2147483647, sourceOfRandomness) may return all positive BigIntegers given enough time.


What will the sourceOfRandomness be is up to you. For example, 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! Note that rolling out your own RNG algorithm will end you up with low quality randomness, so always be sure to use an algorithm that is proven to be decent unless you want the resulting BigInteger(s) to be predictable.

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;
}
```
});

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents