Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# ModInverse Function

Tags:

c#

modulo

c#-4.0

Is there a built in function that would allow me to calculate the modular inverse of a(mod n)? e.g. 19^-1 = 11 (mod 30), in this case the 19^-1 == -11==19;

like image 390
Nook Avatar asked Sep 20 '11 10:09

Nook


2 Answers

Since .Net 4.0+ implements BigInteger with a special modular arithmetics function ModPow (which produces “X power Y modulo Z”), you don't need a third-party library to emulate ModInverse. If n is a prime, all you need to do is to compute:

a_inverse = BigInteger.ModPow(a, n - 2, n)

For more details, look in Wikipedia: Modular multiplicative inverse, section Using Euler's theorem, the special case “when m is a prime”. By the way, there is a more recent SO topic on this: 1/BigInteger in c#, with the same approach suggested by CodesInChaos.

like image 63
Anton Samsonov Avatar answered Sep 22 '22 00:09

Anton Samsonov


int modInverse(int a, int n) 
{
    int i = n, v = 0, d = 1;
    while (a>0) {
        int t = i/a, x = a;
        a = i % x;
        i = x;
        x = d;
        d = v - t*x;
        v = x;
    }
    v %= n;
    if (v<0) v = (v+n)%n;
    return v;
}
like image 36
Samuel Allan Avatar answered Sep 20 '22 00:09

Samuel Allan