Reputation: 91
This is the code to generate a random number from 1 to 10:
int a = (int)(Math.random() * 10) + 1;
But I have been thinking, what if I want to generate a number that is 100 bits randomly? how can I do this with BigInteger datatype?
Upvotes: 1
Views: 732
Reputation: 111259
New answer:
The BigInteger
class has a constructor that you can use to generate a random number with the given number of bits. This is how you could use it:
BigInteger random(int bits) {
Random random = new Random();
return new BigInteger(bits, random);
}
Old answer with a long-winded way of doing the same:
The java.util.Random class has a nextBytes
method to fill an array of bytes with random values. You can use that to generate a BigInteger
with an arbitrary number of bytes.
The complication is, what to do when number of bits isn't a multiple of 8? My suggestion is to generate one byte too much and get rid of the extra bits with a shift operation.
BigInteger random(int bits) {
Random random = new Random();
// One byte too many if not multiple of 8
byte[] bytes = new byte[(bits + 7) / 8];
random.nextBytes(bytes);
BigInteger randomNumber = new BigInteger(1, bytes);
// Get rid of extra bits if not multiple of 8
return randomNumber.shiftRight(bytes.length*8 - bits);
}
Upvotes: 4