我无法弄清楚为什么mod的计算不正确,
我有a=23
,b=86609
,c=17
其中(d=a^c mod b
)。所以根据计算器结果应该是16559
但我得到49432?
public class Mod {
public static void main(String[] args) {
int a=23;
int b=86609;
int c=17;
double d= (Math.pow(a,c)%b);
System.out.print(d);
}
}
答案 0 :(得分:4)
问题不在于模数部分。一旦你去参加战斗部分,你就会得到错误的结果。
23 ^ 17准确地说是1.41050039560662968926103×10 ^ 23。看看Java认为它等于:
1.4105003956066297E23
显然这不够精确。
此问题的解决方案是BigInteger
:
BigInteger a = new BigInteger("23");
BigInteger b = a.modPow(new BigInteger("17"), new BigInteger("86609"));
System.out.println(b);
请记住import java.math.BigInteger;
!
答案 1 :(得分:0)
23 ^ 17对于双倍来说太大了。使用BigInteger
计算它:
public class Main {
public static void main(String[] args) {
int a = 23;
int b = 86609;
int c = 17;
BigInteger big = BigInteger.valueOf(a);
big = big.pow(c);
big = big.mod(BigInteger.valueOf(b));
System.out.print(big);
}
}