英文:
Does anyone know how to generate a number within specific bits in Java?
问题
这是生成从1到10的随机数的代码:
int a = (int)(Math.random() * 10) + 1;
但我一直在思考,如果我想生成一个具有100位的随机数,我该如何使用BigInteger数据类型来实现呢?
英文:
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?
答案1
得分: 4
The BigInteger
类有一个构造函数,您可以使用它来生成具有给定位数的随机数。这是您可以如何使用它的方式:
BigInteger random(int bits) {
Random random = new Random();
return new BigInteger(bits, random);
}
英文:
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);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论