简体   繁体   English

Java Math问题输出不正确

[英]Java Math issue incorrect output

(51^43)Mod77 in scientific calculator gives 2 as the output however, (51 ^ 43)科学计算器中的Mod77给出2作为输出,

(int)(Math.pow(51,43)%(double)77) gives 12 which should be 2 instead. (int)(Math.pow(51,43)%(double)77)给出的12应该是2。

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 . 打印2

A double doesn't have enough precision to hold all the digits of Math.pow(51,43) . double精度没有足够的精度来容纳Math.pow(51,43)所有数字。 So when you take it mod 77 , the answer is prone to significant rounding errors. 因此,当您使用mod 77 ,答案很容易出现明显的舍入错误。

I suggest using BigInteger for arbitrary precision integer arithmetic. 我建议使用BigInteger进行任意精度的整数运算。

Instead of: 代替:

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

do: 做:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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