开发者

Java Math issue incorrect output

开发者 https://www.devze.com 2023-03-29 01:30 出处:网络
(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.

(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

精彩评论

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