Surprising result from Math.pow(65,17) 233

前端 未结 2 1719
自闭症患者
自闭症患者 2021-01-26 05:56

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) % 323         


        
相关标签:
2条回答
  • 2021-01-26 06:27

    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
    
    0 讨论(0)
  • 2021-01-26 06:44

    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;
    }
    
    0 讨论(0)
提交回复
热议问题