Search code examples
c#mathmodulo

C#, Modulo operation gives different result than a calculator


So I wanted to write this method : 142^23 (mod 187), and using any calculator I get the result 65 but with this piece of code : double number = Math.Pow(142, 23) % 187 I get a result of 53. Why is this, and what am I doing wrong here?


Solution

  • Math.Pow(142, 23) is too big to accurately be represented by a double. So your modulus is done on a lossy calculation.

    This will give the correct answer:

    BigInteger.ModPow(142, 23, 187);
    

    BigInteger can be found in the System.Numerics namespace and assembly.

    You can also implement this yourself efficiently if you want like so for integers of the size you were using in your question.

    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 does something more clever with binary exponentiation which will work better with truly huge number.