Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 742
Tony Avatar asked Dec 06 '25 08:12

Tony


2 Answers

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.

like image 132
NPE Avatar answered Dec 08 '25 21:12

NPE


It'd be pretty simple to just write a mod function which does what you require. Example here:

private int mod(int x, int y)
{
    int result = x % y;
    if (result < 0)
    {
        result += y;
    }
    return result;
}

It's much clearer than using % 11 + 11) % 11, and the operation makes sense immediately when you look at it. mod(32, 11) is more clearly 32 mod 11 than (32 % 11 + 11) % 11, and it saves an extra % operation.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!