I am unsure about how to generate a random n digit integer in Java using the BigInteger class.
views:
179answers:
5The 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)
.
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))
Take a string with 5000 digits in it then convert it into BigInteger.
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.
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.