来自Math.pow(65,17)%3233的令人惊讶的结果
由于某些原因,当处理大数字时,模数运算符不会给我正确的输出,看看代码
double x = Math.pow(65,17) % 3233;
输出应该是2790
但是输出是887.0
我确定它有点傻但我无法绕过它。 提前致谢
Math.pow(65, 17)
的结果不能完全表示为double
,而是四舍五入到最接近的数字。
pow(a, b) % c
操作称为“模幂运算”。 维基百科页面包含许多关于如何计算它的想法。
这是一种可能性:
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