Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I generate a random n digit integer in Java using the BigInteger class?

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

like image 545
makaveli2178 Avatar asked Sep 14 '10 13:09

makaveli2178


People also ask

How do you create a random BigInteger?

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.

How do you generate a random integer value in Java?

In order to generate Random Integer Numbers in Java, we use the nextInt() method of the java. util. Random class. This returns the next random integer value from this random number generator sequence.


3 Answers

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))
like image 136
Eyal Schneider Avatar answered Sep 30 '22 19:09

Eyal Schneider


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.

like image 25
Carl Avatar answered Sep 30 '22 17:09

Carl


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).

like image 38
Jon Skeet Avatar answered Sep 30 '22 19:09

Jon Skeet