Java Language BigInteger Generating random BigIntegers

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

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


Got any Java Language Question?