开发者

Java Math issue incorrect output

(51^43)Mod77 in scientific calculator gives 2 as the output however,

(int)(Ma开发者_StackOverflow中文版th.pow(51,43)%(double)77) gives 12 which should be 2 instead.

Can you please help ?


    final BigInteger base = BigInteger.valueOf(51);
    final BigInteger exponent = BigInteger.valueOf(43);
    final BigInteger modulus = BigInteger.valueOf(77);
    System.out.println(base.modPow(exponent, modulus));

prints 2.


A double doesn't have enough precision to hold all the digits of Math.pow(51,43). So when you take it mod 77, the answer is prone to significant rounding errors.

I suggest using BigInteger for arbitrary precision integer arithmetic.


Instead of:

(int)(Math.pow(51,43)%(double)77)

do:

(int)(Math.pow(51,43))%((double)77)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜