为了在 Java 中生成随机的 BigInteger,让我们先设置一个 min 和 max 值-
BigInteger maxLimit = new BigInteger("5000000000000"); BigInteger minLimit = new BigInteger("25000000000");
现在,减去min和max−
BigInteger bigInteger = maxLimit.subtract(minLimit); //声明一个 Random 对象并查找 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