Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java random number generator

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.

like image 515
Ryan Sayles Avatar asked Feb 19 '23 03:02

Ryan Sayles


2 Answers

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.

like image 83
Sergey Kalinichenko Avatar answered Mar 06 '23 07:03

Sergey Kalinichenko


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)
like image 32
codaddict Avatar answered Mar 06 '23 06:03

codaddict