How to generate a random BigInteger value in Java?


To generate random BigInteger in Java, let us first set a min and max value −

BigInteger maxLimit = new BigInteger("5000000000000");
BigInteger minLimit = new BigInteger("25000000000");

Now, subtract the min and max −

BigInteger bigInteger = maxLimit.subtract(minLimit);
Declare a Random object and find the length of the maxLimit:
Random randNum = new Random();
int len = maxLimit.bitLength();

Now, set a new B integer with the length and the random object created above.

Example

 Live Demo

import java.math.BigInteger;
import java.util.Random;
public class Demo {
   public static void main(String[] args) {
      BigInteger maxLimit = new BigInteger("5000000000000");
      BigInteger minLimit = new BigInteger("25000000000");
      BigInteger bigInteger = maxLimit.subtract(minLimit);
      Random randNum = new Random();
      int len = maxLimit.bitLength();
      BigInteger res = new BigInteger(len, randNum);
      if (res.compareTo(minLimit) < 0)
         res = res.add(minLimit);
      if (res.compareTo(bigInteger) >= 0)
         res = res.mod(bigInteger).add(minLimit);
         System.out.println("The random BigInteger = "+res);
   }
}

Output

The random BigInteger = 3874699348568

Updated on: 30-Jul-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements