How to Generate Random BigInteger Values Within a Custom Range in Java
To generate random BigInteger values within a specified range, particularly when the upper limit (n) is not a power of 2, the constructor BigInteger(int numBits, Random rnd) can be employed.
To achieve this, a loop is necessary:
<code class="java">BigInteger randomNumber; do { randomNumber = new BigInteger(upperLimit.bitLength(), randomSource); } while (randomNumber.compareTo(upperLimit) >= 0);</code>
This approach provides uniform distribution within the specified range and typically requires less than two iterations.
For efficiency, the number of iterations can be limited:
<code class="java">int nlen = upperLimit.bitLength(); BigInteger nm1 = upperLimit.subtract(BigInteger.ONE); BigInteger randomNumber, temp; do { temp = new BigInteger(nlen + 100, randomSource); randomNumber = temp.mod(upperLimit); } while (s.subtract(randomNumber).add(nm1).bitLength() >= nlen + 100);</code>
While this version ensures rapid completion in almost all cases, it introduces a more computationally expensive mod() operation. Therefore, the choice between the two approaches depends on the specific RNG instance used.
The above is the detailed content of How to Generate Random BigInteger Values Within a Custom Range in Java?. For more information, please follow other related articles on the PHP Chinese website!