title: How to generate a random BigInteger value in Java?
body: <p>I need to generate arbitrarily large random integers in the range 0 (inclusive) to n (exclusive).  My initial thought was to call <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/Random.html#nextDouble%28%29" rel="noreferrer"><code>nextDouble</code></a> and multiply by n, but once n gets to be larger than 2<sup>53</sup>, the results would no longer be uniformly distributed.</p>
  
  <p><a href="http://java.sun.com/j2se/1.5.0/docs/api/java/math/BigInteger.html#BigInteger%28int,%20java.util.Random%29" rel="noreferrer"><code>BigInteger</code></a> has the following constructor available:</p>
  
  <pre><code>public BigInteger(int numBits, Random rnd)
  </code></pre>
  
  <blockquote>
    <p>Constructs a randomly generated BigInteger, uniformly distributed over the range 0 to (2<sup>numBits</sup> - 1), inclusive.</p>
  </blockquote>
  
  <p>How can this  be used to get a random value in the range 0 - n, where n is not a power of 2?</p>