簡體   English   中英

Math.pow(65,17)%3233的令人驚訝的結果

[英]Surprising result from Math.pow(65,17) % 3233

由於某些原因,在處理大數時,模運算符沒有給我正確的輸出,請看一下代碼

double x = Math.pow(65,17) % 3233;

輸出應該是2790但輸出是887.0

我確信它有些愚蠢,但我無法解決它。 提前致謝

Math.pow(65, 17)的結果不能完全表示為double ,並且四舍五入到可以的最接近的數字。

pow(a, b) % c運算稱為“模冪”。 Wikipedia頁面包含許多有關如何進行計算的想法。

這是一種可能性:

public static int powmod(int base, int exponent, int modulus) {
    if (exponent < 0)
        throw new IllegalArgumentException("exponent < 0");
    int result = 1;
    while (exponent > 0) {
        if ((exponent & 1) != 0) {
            result = (result * base) % modulus;
        }
        exponent >>>= 1;
        base = (base * base) % modulus;
    }
    return result;
}

你可以這樣使用int

int n = 65;
for (int i = 1; i < 17; i++)
    n = n * 65 % 3233;
System.out.println(n);

或BigInteger之類的

System.out.println(BigInteger.valueOf(65).pow(17).mod(BigInteger.valueOf(3233)));

都打印

2790

暫無
暫無

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

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