有没有解决这个问题的方法?为什么它返回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)
因此,您不需要进行繁重的计算.只是数学.
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)
该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不是素数)
| 归档时间: |
|
| 查看次数: |
490 次 |
| 最近记录: |