Jasmine Jasmine - 1 year ago 66
Java Question

Generating random unique BigIntegers within a specified range?

I'm new to using BigInteger, so I'm trying my best reading through the documentation for it. I'm still confused however. I need to generate 500 random integers between the range of 2^70 and 2^80 and I don't know how to set a range for BigIntegers.

I'm getting the possible duplicate messages, so I guess I should add that I've already looked at the solutions in this one and still don't understand how to solve my issue: How to generate a random BigInteger value in Java?

Answer Source

There is a built-in method to generate a random BigInteger between 0 and 2^n - 1.

You can use that in a loop to generate numbers up to 2^80.

The chance that a number will fall below 2^70 is very small ( ~ 0.1%). If that happens (and with 500 iterations it might very well), just draw another one.

This will give you a uniform distribution of random numbers between 2^70 and 2^80.

The chance that a number will repeat is almost nonexistent. If you feel that it cannot be ignored, check your previous numbers for duplicates, and draw again.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download