如何在 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
廣告