Java总是给我错误的结果
我写了这行代码:
System.out.println(Math.pow(7, 23) % 143); // 7^23 mod 143
我预计输出为2
但输出为93.0
。 有人知道我做错了什么吗?
数字“溢出” double
,这是Math.pow()
期望并返回的。 改为使用BigInteger
:
BigInteger.valueOf(7) .pow(23) .mod(BigInteger.valueOf(143))
或者按照@Felk的建议,只需一步:
BigInteger.valueOf(7) .modPow(BigInteger.valueOf(23), BigInteger.valueOf(143))
Math.pow
的结果是double
,它有64位; 其中53个是尾数位。 这意味着任何大于2^53-1 = 9007199254740991
都不能精确地表示为double。
7 ^ 23大于2 ^ 53-1(实际上它仅略大于2 ^ 64),因此无法精确表示。 因此, %
的结果不是您所期望的。
正如@Costi已经建议的那样使用BigInteger
。
如果中间取幂结果太大而无法保存在变量中,请使用模幂运算算法 。
System.out.println(powMod(7, 23, 143)); // = 2 // Example from Wikipedia with minor changes private static int powMod(int base, int exponent, int modulus) { if (modulus == 1) return 0; base %= modulus; int result = 1; while (exponent > 0) { if ((exponent & 1) == 1) result = (result * base) % modulus; exponent >>= 1; base = (base * base) % modulus; } return result; }