>假设我从用户那里输入"8",我应该能够生成一个长度为8位的随机BigInteger。假设我输入"20",我应该能够生成一个长度为 20 位的随机 BigInteger。我怎样才能做到这一点?
我有以下代码,我从示例中引用了这些代码。
int SIZE = 512;
p = new BigInteger(SIZE, 15, new Random());
q = new BigInteger(SIZE, 15, new Random());
谁能告诉我这些论点是什么意思?或者你能建议一种更简单的方法来实现这一目标吗?
BigInteger(int bitLength, 确定性, 随机 rnd)
构造一个随机生成的正 BigInteger,该整数可能是素数,具有指定的 bitLength。建议优先使用此构造函数的 probablePrime 方法,除非迫切需要指定确定性。
参数:
bitLength - 返回的 BigInteger 的 bitLength。
确定性 - 衡量调用方愿意容忍的不确定性。新的 BigInteger 表示素数的概率将超过 (1 - 1/2)。此构造函数的执行时间与此参数的值成正比。
RND - 用于选择要测试素数的候选者的随机位源。
直接取自甲骨文网站,希望这就是您要找的。
整数解
public static int randInt(int min, int max) {
// Usually this can be a field rather than a method variable
Random rand = new Random();
// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
所以如果你需要8位随机数
调用此函数,范围为 8 位数字i.e
最小的 8 位 # 和最高的 8 位数字。
例如
randInt(10000000, 99999999)
来源:范围的随机数代码取自此处
如何在 Java 中生成特定范围内的随机整数?
你也可以看看nextLong()
。这些是统一生成的随机数
http://docs.oracle.com/javase/6/docs/api/java/util/Random.html#nextLong()