How to generate a random BigInteger value in Java?

Posted by Bill the Lizard on Stack Overflow See other posts from Stack Overflow or by Bill the Lizard
Published on 2010-02-18T16:08:48Z Indexed on 2010/04/24 0:03 UTC
Read the original article Hit count: 190

Filed under:
|
|

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?

© Stack Overflow or respective owner

Related posts about java

Related posts about random