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

丶灬走出姿态 提交于 2019-12-02 16:15:04

问题


For some reason when dealing with large numbers, the modulus operator doesnt give me the correct output, have a look at the code

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

The output is supposed to be 2790 But the output is 887.0

I am sure its something silly but i cant get around it. Thanks in advance


回答1:


The result of Math.pow(65, 17) cannot be represented exactly as a double, and is getting rounded to the nearest number that can.

The pow(a, b) % c operation is called "modular exponentiation". The Wikipedia page contains lots of ideas for how you might go about computing it.

Here is one possibility:

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;
}



回答2:


You can use int like this

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

or BigInteger like

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

both print

2790


来源:https://stackoverflow.com/questions/13896614/surprising-result-from-math-pow65-17-3233

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!