Home > Java > javaTutorial > body text

How to Generate Random BigInteger Values Within a Custom Range in Java?

Linda Hamilton
Release: 2024-10-25 07:43:29
Original
309 people have browsed it

How to Generate Random BigInteger Values Within a Custom Range in Java?

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

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

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!

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!