首頁  >  文章  >  Java  >  如何在 Java 中產生自訂範圍內的隨機 BigInteger 值?

如何在 Java 中產生自訂範圍內的隨機 BigInteger 值?

Linda Hamilton
Linda Hamilton原創
2024-10-25 07:43:29310瀏覽

How to Generate Random BigInteger Values Within a Custom Range in Java?

如何在Java 中產生自訂範圍內的隨機BigInteger 值

產生指定範圍內的隨機BigInteger 值,特別是當上限limit (n) 不是2 的冪,可以使用建構子BigInteger(int numBits, Random rnd)。

要實現這一點,需要一個循環:

<code class="java">BigInteger randomNumber;
do {
    randomNumber = new BigInteger(upperLimit.bitLength(), randomSource);
} while (randomNumber.compareTo(upperLimit) >= 0);</code>

這個方法提供指定範圍內的均勻分佈,通常需要少於兩次迭代。

為了提高效率,可以限制迭代次數:

<code class="java">int nlen = upperLimit.bitLength();
BigInteger nm1 = upperLimit.subtract(BigInteger.ONE);
BigInteger randomNumber, temp;
do {
    temp = new BigInteger(nlen + 100, randomSource);
    randomNumber = temp.mod(upperLimit);
} while (s.subtract(randomNumber).add(nm1).bitLength() >= nlen + 100);</code>

雖然此版本確保在幾乎在所有情況下,它都會引入計算成本更高的 mod() 操作。因此,兩種方法之間的選擇取決於所使用的特定 RNG 實例。

以上是如何在 Java 中產生自訂範圍內的隨機 BigInteger 值?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn