Is it possible to have a user choose the number of digits of a random number, specifically a random Big Integer? For example if the user wants it to be 15 digits long the random number generator would only produce 15 digit long Big Integers.
You can use the constructor of BigInteger
where you specify the number of binary digits: BigInteger(int numBits, Random rnd)
. You need roughly ten binary digits for each three decimal digits that the user wants. For example, if you need a 30-digit random BigInt
, use 100 binary digits.
You can cut off the unnecessary digits by using remainder(10^30)
, and do it in a loop to ensure that the initial digit is not zero, ensuring the correct number of digits, like this:
Random rnd = new Random(123);
BigInteger tenPow30 = new BigInteger("10").pow(30);
BigInteger min = new BigInteger("10").pow(29);
BigInteger r;
do {
r = new BigInteger(100, rnd).remainder(tenPow30);
} while (r.compareTo(min) < 0);
System.out.println(r);
Link to a demo.
You can always generate individual digits of the number randomly. This way for a 15 digit number you can generate 15 digits randomly and then form the number.
Another way:
Lets change the problem to generate random 5 digit number.
Min = 10000
Max = 99999
Now generate a random number between 0
and Max - Min
which is 0
and 89999
and add it to Min
.
Random = Min + Math.random() * (Max - Min)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With