所以我想写这个方法:142^23 (mod 187),使用任何计算器我得到结果 65,但使用这段代码:
双数 = Math.Pow(142, 23) % 187
我得到 53 的结果。这是为什么,我在这里做错了什么?
最佳答案
Math.Pow(142, 23)
太大而无法用 double 表示。所以你的模数是在有损计算上完成的。
这将给出正确答案:
BigInteger.ModPow(142, 23, 187);
BigInteger
可以在 System.Numerics
命名空间和程序集中找到。
如果你想像你在问题中使用的整数那样,你也可以自己有效地实现它。
private static int ModPow(int basenum, int exponent, int modulus)
{
if (modulus == 1)
{
return 0;
}
int result = 1;
for (var i = 0; i < exponent; i++)
{
result = (result * basenum) % modulus;
}
return result;
}
BigInteger
在二进制求幂方面做了一些更聪明的事情,这将更好地处理真正巨大的数字。
关于C#,模运算给出与计算器不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49456119/