How to generate a random BigInteger value in Java?

2019-01-02 23:49发布

I need to generate arbitrarily large random integers in the range 0 (inclusive) to n (exclusive). My initial thought was to call nextDouble and multiply by n, but once n gets to be larger than 253, the results would no longer be uniformly distributed.

BigInteger has the following constructor available:

public BigInteger(int numBits, Random rnd)

Constructs a randomly generated BigInteger, uniformly distributed over the range 0 to (2numBits - 1), inclusive.

How can this be used to get a random value in the range 0 - n, where n is not a power of 2?

7条回答
爷、活的狠高调
2楼-- · 2019-01-03 00:20

Just use modular reduction

new BigInteger(n.bitLength(), new SecureRandom()).mod(n)
查看更多
登录 后发表回答