javamoduloinverse

Java modular inverse


I'm doing some error correction in Java and to cut a long story short;

Under mod 11:

-4 mod 11 = 7

This I've confirmed by using Google's calculator and a couple of online modulo calculators, but I cannot for the life of me figure out how to do it in Java.

I'm thinking that I need to use an inverse table to find the correct number but I seem to be going round in circles.

Any input would be appreciated.

Thank in advance

Tony


Solution

  • The following will compute n mod 11 for any integer n:

    (n % 11 + 11) % 11
    

    The result of n % 11 is in the range -10...10. The subsequent addition and the second modulo operation add 11 to n % 11 iff the latter is negative.

    This formula works for any base: just replace 11 with another positive integer.