Java Algorithms How to - Generate a random BigInteger value








Question

We would like to know how to generate a random BigInteger value.

Answer

/*ww w.j  a  v a 2s.  co m*/
import java.math.BigInteger;
import java.util.Random;

public class Main {
  public static void main(String[] args) {
    BigInteger bigInteger = new BigInteger("2000000000000");// uper limit
    BigInteger min = new BigInteger("1000000000");// lower limit
    BigInteger bigInteger1 = bigInteger.subtract(min);
    Random rnd = new Random();
    int maxNumBitLength = bigInteger.bitLength();

    BigInteger aRandomBigInt;

    aRandomBigInt = new BigInteger(maxNumBitLength, rnd);
    if (aRandomBigInt.compareTo(min) < 0)
      aRandomBigInt = aRandomBigInt.add(min);
    if (aRandomBigInt.compareTo(bigInteger) >= 0)
      aRandomBigInt = aRandomBigInt.mod(bigInteger1).add(min);
    
    System.out.println(aRandomBigInt);
  }
}

The code above generates the following result.