所以我想写一个方法: 142^23 (mod 187),使用任何计算器我得到结果65,但是用这段代码:double number = Math.Pow(142, 23) % 187我得到了53的结果。为什么,我在这里做错什么了?
发布于 2018-03-23 18:29:03
Math.Pow(142, 23)太大了,无法精确地用双人表示。所以你的模数是在有耗的计算上做的。
这将给出正确的答案:
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用二进制指数做了一些更聪明的事情,这将对真正庞大的数字更好地工作。
https://stackoverflow.com/questions/49456119
复制相似问题