Generating Random BigIntegers in Java
Question:
How do you generate arbitrarily large random BigInteger values in the range of 0 to n (excluding n), where n is not a power of 2?
Answer:
Utilizing BigInteger's constructor that takes a bit count and an instance of a Random generator, you can create such values:
public BigInteger(int numBits, Random rnd)
However, to obtain values within the desired range, it is necessary to employ a loop:
BigInteger randomNumber; do { randomNumber = new BigInteger(upperLimit.bitLength(), randomSource); } while (randomNumber.compareTo(upperLimit) >= 0);
On average, this loop operates in less than two iterations, ensuring uniform distribution.
Edit:
For situations where the Random generator is performance-intensive, you can implement the following approach:
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);
While this method significantly reduces the likelihood of multiple loop iterations (less than one chance in 2^100), it utilizes the computationally expensive mod() operation. Therefore, this approach may be less efficient than the previous one if the supplied Random instance has low performance overhead.
The above is the detailed content of How to Generate Arbitrarily Large Random BigIntegers in a Specific Range in Java?. For more information, please follow other related articles on the PHP Chinese website!