簡體   English   中英

BigInteger.pow(大整數)?

[英]BigInteger.pow(BigInteger)?

我正在用 Java 玩數字,想看看我能做多大的數字。 我的理解是 BigInteger 可以容納無限大小的數字,只要我的計算機有足夠的內存來容納這樣的數字,對嗎?

我的問題是 BigInteger.pow 只接受一個 int,而不接受另一個 BigInteger,這意味着我只能使用不超過 2,147,483,647 的數字作為指數。 是否可以這樣使用 BigInteger 類?

BigInteger.pow(BigInteger)

謝謝。

您可以編寫自己的,使用重復平方

BigInteger pow(BigInteger base, BigInteger exponent) {
  BigInteger result = BigInteger.ONE;
  while (exponent.signum() > 0) {
    if (exponent.testBit(0)) result = result.multiply(base);
    base = base.multiply(base);
    exponent = exponent.shiftRight(1);
  }
  return result;
}

可能不適用於負基數或指數。

您只能在Java中通過模運算來做到這一點,這意味着您可以做 a a^b mod c ,其中a,b,cBigInteger數。

這是使用以下方法完成的:

 BigInteger modPow(BigInteger exponent, BigInteger m) 

在此處閱讀BigInteger.modPow文檔。

BigInteger 的底層實現僅限於 (2^31-1) * 32 位值。 這幾乎是 2^36 位。 您將需要 8 GB 的內存來存儲它,並且多次使用它來執行任何操作,例如 toString()。

順便說一句:您將永遠無法讀取這樣的數字。 如果您嘗試將其打印出來,則可能需要一生的時間才能閱讀。

我可以建議你使用 BigInteger modPow(BigInteger exponent, BigInteger m)

假設您有 BigInteger X 和 BigInteger Y,並且您想要計算 BigInteger Z = X^Y。

得到一個大的素數 P >>>> X^Y 並做 Z = X.modPow(Y,P);

java不會讓你做BigInteger.Pow(BigInteger),但你可以把它放在一個循環中的最大整數上,看看在哪里拋出了ArithmeticException或由於內存不足而引發的其他錯誤。

2^2,147,483,647 至少有 500000000 位,實際上計算 pow 是 NPC 問題,[Pow 是 NPC 的輸入長度,2 個輸入 (m,n),它們可以用 O(logm + logn) 編碼,最多可以占用nlog(m) (最后答案占用 n log(m) 空間)這不是輸入和計算大小之間的多項式關系],有一些簡單的問題實際上並不容易,例如sqrt(2)是某種他們,你不能指定真正的精度(所有精度),即 BigDecimal 說可以計算所有精度,但它不能(事實上)因為到目前為止沒有人解決這個問題。

請務必閱讀之前的答案和評論,並理解為什么不應該在生產級應用程序上嘗試這樣做。 以下是僅可用於測試目的的有效解決方案:

指數大於或等於 0

BigInteger pow(BigInteger base, BigInteger exponent) {
    BigInteger result = BigInteger.ONE;
    for (BigInteger i = BigInteger.ZERO; i.compareTo(exponent) != 0; i = i.add(BigInteger.ONE)) {
        result = result.multiply(base);
    }
    return result;
}

這將適用於正面和負面的基地。 您可能希望根據需要處理0 的 0 次方,因為這在技術上是未定義的。

指數可以是正數也可以是負數

BigDecimal allIntegersPow(BigInteger base, BigInteger exponent) {
    if (BigInteger.ZERO.compareTo(exponent) > 0) {
        return BigDecimal.ONE.divide(new BigDecimal(pow(base, exponent.negate())), 2, RoundingMode.HALF_UP);
    }
    return new BigDecimal(pow(base, exponent));
}

這重用了第一種方法來返回帶 2 個小數位的 BigDecimal,您可以根據需要定義比例和舍入模式。

同樣,您不應該在現實生活中的生產級系統中這樣做。

對於從 Groovy 方面偶然發現這一點的任何人,完全可以將 BigInteger 傳遞給 BigInteger.pow()。

groovy> def a = 3G.pow(10G) 
groovy> println a 
groovy> println a.class 

59049
class java.math.BigInteger

http://docs.groovy-lang.org/2.4.3/html/groovy-jdk/java/math/BigInteger.html#power%28java.math.BigInteger%29

只需使用 .intValue() 如果您的 BigInteger 被命名為 BigValue2,那么它將是 BigValue2.intValue()

所以要回答你的問題,它是

BigValue1.pow(BigValue2.intValue())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM