Question

I am unsure about how to generate a random n digit integer in Java using the BigInteger class.

Was it helpful?

Solution

private static Random rnd = new Random();

public static String getRandomNumber(int digCount) {
    StringBuilder sb = new StringBuilder(digCount);
    for(int i=0; i < digCount; i++)
        sb.append((char)('0' + rnd.nextInt(10)));
    return sb.toString();
}

And then you can use it:

new BigInteger(getRandomNumber(10000))

OTHER TIPS

According to the docs, there is a constructor to do what you want in java 6: BigInteger(int, java.util.Random)

To that, you need only add a randomly selected 5000th digit-i.e. Use the rng constructor to 4999 digits, the add the last in via a separate random process. Actually, since you want to just sample performance for large values, you could generate the bits, and tack a one bit on the big end, rather than slave to decimal notation.

The simplest way would probably to be to fill a char[] array with 5000 random digits, convert that to a string, and then call the BigInteger(String) constructor.

If any of those steps gives you problems, please give more details.

Alternatively, you could do something like this:

Random rng = new Random(); // But use one instance throughout your app
BigInteger current = BigInteger.ZERO;
for (int i = 0; i < 5000; i++) {
    BigInteger nextDigit = BigInteger.valueOf(rng.nextInt(10));
    current = current.multiply(BigInteger.TEN).add(nextDigit);
}

I suspect that would be rather less efficient though.

You could reduce the number of steps required by generating nine random digits at a time, with rng.nextInt(1000000000).

Here are two versions, one takes a Random as parameter (in case you want to re-use it):

public static BigInteger getRandomNumber(final int digCount){
    return getRandomNumber(digCount, new Random());
}

public static BigInteger getRandomNumber(final int digCount, Random rnd){
    final char[] ch = new char[digCount];
    for(int i = 0; i < digCount; i++){
        ch[i] =
            (char) ('0' + (i == 0 ? rnd.nextInt(9) + 1 : rnd.nextInt(10)));
    }
    return new BigInteger(new String(ch));
}

The resulting BigInteger will always have the specified length.

If n is between 1 to 12 then following method helps

private String getRandom(int length) {
    if (length < 1 && length > 12) {
        throw new IllegalArgumentException("Random number generator length should be between 1 to 12");
    }
    long nextLong = Math.abs(random.nextLong());
    return String.valueOf(nextLong).substring(0, length);
}

One more thing to note is that it is not well tested code.

Take a string with 5000 digits in it then convert it into BigInteger.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top