如何在 Java 中生成一个随机 BigInteger 值?
要生成 Java 中的随机 BigInteger,我们首先设置一个最小值和一个最大值 −
BigInteger maxLimit = new BigInteger("5000000000000");
BigInteger minLimit = new BigInteger("25000000000");现在,减去最小值和最大值 −
BigInteger bigInteger = maxLimit.subtract(minLimit); Declare a Random object and find the length of the maxLimit: Random randNum = new Random(); int len = maxLimit.bitLength();
现在,使用长度和上面创建的随机对象设置一个新的 B 整数。
示例
import java.math.BigInteger;
import java.util.Random;
public class Demo {
public static void main(String[] args) {
BigInteger maxLimit = new BigInteger("5000000000000");
BigInteger minLimit = new BigInteger("25000000000");
BigInteger bigInteger = maxLimit.subtract(minLimit);
Random randNum = new Random();
int len = maxLimit.bitLength();
BigInteger res = new BigInteger(len, randNum);
if (res.compareTo(minLimit) < 0)
res = res.add(minLimit);
if (res.compareTo(bigInteger) >= 0)
res = res.mod(bigInteger).add(minLimit);
System.out.println("The random BigInteger = "+res);
}
}输出
The random BigInteger = 3874699348568
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP