如何在java中获取大数字的剩余部分

use*_*091 4 java

有没有解决这个问题的方法?为什么它返回541而不是3.

public class Test {
    public static void main(String[] args) {
        double a = Math.pow(3, 561);

        // it returns 541 instead of 3
        System.out.println(a % 561);
    }
}
Run Code Online (Sandbox Code Playgroud)

Kon*_*kov 11

根据费马的小定理:

Math.pow(a, p) % p == a % p
Run Code Online (Sandbox Code Playgroud)

所以:

Math.pow(3, 561) % 561 = 3 % 561 = 3
Run Code Online (Sandbox Code Playgroud)

因此,您不需要进行繁重的计算.只是数学.

  • 我也忽略了这一点(很高兴这里有很多眼睛).因此,例如,`Math.pow(3,560)%560 = 3`确实**不**持... (3认同)
  • 特别是当重计算超出所用数据类型的精度时. (2认同)

Chr*_*tin 6

doubles实际上并不像整数那样.Java的真正整数类型是java.math.BigInteger.

public static void main(String[] args) {
    BigInteger a = new BigInteger("3").pow(561);
    System.out.println(a.mod(new BigInteger("561")));
}
Run Code Online (Sandbox Code Playgroud)


Mar*_*o13 6

BigInteger课程有一个专门的方法:

import java.math.BigInteger;

public class BigModPow
{
    public static void main(String[] args)
    {
        BigInteger b = new BigInteger("3");
        BigInteger e = new BigInteger("561");
        BigInteger m = new BigInteger("560");
        BigInteger result = b.modPow(e, m);
        System.out.println(result);
    }
}
Run Code Online (Sandbox Code Playgroud)

(编辑:我将模数改为与指数不同的值,以表明计算了一个非平凡的结果 - 尽管561不是素数)