问题
I am unsure about how to generate a random n digit integer in Java using the BigInteger class.
回答1:
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))
回答2:
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.
回答3:
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)
.
回答4:
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.
回答5:
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.
回答6:
Take a string with 5000 digits in it then convert it into BigInteger.
来源:https://stackoverflow.com/questions/3709521/how-do-i-generate-a-random-n-digit-integer-in-java-using-the-biginteger-class