Home > Java > javaTutorial > body text

## How do you generate random BigInteger values within a specific range in Java?

Mary-Kate Olsen
Release: 2024-10-25 07:18:29
Original
302 people have browsed it

## How do you generate random BigInteger values within a specific range in Java?

Generating Random BigInteger Values in Java

In scenarios where generating arbitrarily large random integers within a specified range is necessary, a common approach might involve using nextDouble() and multiplying the output by the desired limit. However, this method becomes problematic for values exceeding 2^53, leading to non-uniform distribution.

To overcome this limitation, Java provides the BigInteger class, which offers a constructor that generates random numbers uniformly distributed between 0 and (2^numBits - 1), inclusive.

Generating a Random Value Within a Non-Power-of-2 Range

To generate a random value in the range 0 to n, where n is not a power of 2, a simple loop can be employed:

<code class="java">BigInteger randomNumber;
do {
    randomNumber = new BigInteger(upperLimit.bitLength(), randomSource);
} while (randomNumber.compareTo(upperLimit) >= 0);</code>
Copy after login

This iterative approach ensures a uniform distribution within the desired range. Typically, only one or two iterations are required.

Limiting Iterations in the Loop

For scenarios where the random number generator is computationally expensive, the number of iterations in the loop can be restricted as follows:

<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

This modified version is highly unlikely to require multiple iterations (probability less than 2^100). However, it incurs a computational penalty due to the mod() operation. Thus, it is recommended only if the random number generator is particularly slow.

The above is the detailed content of ## How do you generate random BigInteger values within 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!