Home > Java > javaTutorial > body text

How to Generate Arbitrarily Large Random BigIntegers in a Specific Range in Java?

Linda Hamilton
Release: 2024-10-25 01:02:30
Original
416 people have browsed it

How to Generate Arbitrarily Large Random BigIntegers in a Specific Range in Java?

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)
Copy after login

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);
Copy after login

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);
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!