生成 n 位或更多位的随机数
Generate random number of n digits or more
我看到很多生成特定范围 [min-max] 内的随机数的例子,但我需要 java 生成 n 位或更多位随机数的代码,所以在这种情况下 min= 10000000
和 no max
.
注意 - 我正在使用 BigInteger
BigInteger
在其构造函数之一中接受十进制字符串。生成单个数字并将它们附加到字符串。当你的字符串中有足够的数字时,从字符串中创建你的 BigInteger
。您可能希望将第一个数字限制在 [1 .. 9] 中以避免前导零,具体取决于您的具体要求。
您可以使用构造函数BigInteger(int numBits, Random rnd)
生成N位正随机数。
因为你想要最小值,你可以将其作为偏移量添加到生成的数字中:
Random random = ThreadLocalRandom.current();
BigInteger base = BigInteger.valueOf(10000000); // min
int randomBits = 50; // set as many bits as you fancy
BigInteger rnd = base.add(new BigInteger(randomBits, random));
我看到很多生成特定范围 [min-max] 内的随机数的例子,但我需要 java 生成 n 位或更多位随机数的代码,所以在这种情况下 min= 10000000
和 no max
.
注意 - 我正在使用 BigInteger
BigInteger
在其构造函数之一中接受十进制字符串。生成单个数字并将它们附加到字符串。当你的字符串中有足够的数字时,从字符串中创建你的 BigInteger
。您可能希望将第一个数字限制在 [1 .. 9] 中以避免前导零,具体取决于您的具体要求。
您可以使用构造函数BigInteger(int numBits, Random rnd)
生成N位正随机数。
因为你想要最小值,你可以将其作为偏移量添加到生成的数字中:
Random random = ThreadLocalRandom.current();
BigInteger base = BigInteger.valueOf(10000000); // min
int randomBits = 50; // set as many bits as you fancy
BigInteger rnd = base.add(new BigInteger(randomBits, random));