简体   繁体   中英

Java Math issue incorrect output

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

(int)(Math.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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM