C#,Modulo操作比计算器产生不同的结果

Joh*_*ith 1 c# math mod

所以我想写这个方法:142 ^ 23(MOD 187),并使用任何计算器我得到的结果是65,但与这段代码: double number = Math.Pow(142, 23) % 187 我得到的53的结果为什么会这样,什么我错了在这里做?

vcs*_*nes 11

Math.Pow(142, 23)太大而不能准确地用双精度表示.所以你的模数是在有损计算上完成的.

这将给出正确答案:

BigInteger.ModPow(142, 23, 187);
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

BigInteger 用二进制求幂做一些更聪明的东西,它可以用真正庞大的数字更好地工作.