Java random number generator

Is it possible for the user to select the number of digits of a random number, in particular a random large integer? For example, if the user wants him to be 15 digits, the random number generator will only generate 15-digit long large integers.

+4
source share
4 answers

You can use the BigInteger constructor, where you specify the number of binary digits: BigInteger(int numBits, Random rnd) . You need approximately ten binary digits for every 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 unnecessary digits with remainder(10^30) and do it in a loop to ensure that the starting digit is not zero, providing the correct number of digits, for example:

 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 the demo.

+5
source

You can always generate individual digits of a number randomly. Thus, for a 15-digit number, you can arbitrarily generate 15 digits, and then form the number.

Another way:

Allows you to change the problem to create a random 5-digit number.

 Min = 10000 Max = 99999 

Now create a random number between 0 and Max - Min , which is 0 and 89999 , and add it to Min .

 Random = Min + Math.random() * (Max - Min) 
+4
source

Here are the steps:

  • Creating n numbers
  • Merge them with StringBuilder
  • Create your number using BigInteger(String)

Here is the code:

 public static BigInteger randomBigInt(int digits, Random rand) { StringBuilder sb = new StringBuilder(digits); // First digit can't be 0 sb.append(rand.nextInt(9) + 1); int limit = digits - 1; for (int i = 0; i < limit; i++) sb.append(rand.nextInt(10)); return new BigInteger(sb.toString()); } 

This generates each digit separately and adds them to a StringBuilder (unlike int or something that might cause buffer overflow problems), and then uses the resulting String to create BigInteger . Also note that the first digit will never be 0.

0
source

Using a random generator similar to the RandomUtil class here , you can create random numbers between some values ​​and much more.

For example, using this code, there will be 15 digits in the range from min = 100000000000000 max = 999999999999999:

 BigInteger number = RandomUtil.getRandomBigInteger(new BigInteger("100000000000000"), new BigInteger("999999999999999"), false); 
-1
source

Source: https://habr.com/ru/post/1434389/


All Articles