When the modulus is a prime number can inverse yuan by Fermat's little theorem.
When modulus is a composite number, Fermat's little theorem fails in most cases, this time, only the modulus co-prime numbers have an inverse element (composite number satisfy Fermat's little theorem called pseudo prime numbers, we need to discuss this issue open a new blog up).
(For a number n, and with it all of its mass is less than the number of the multiplicative group modulo n form a cross)
gcd is the greatest common divisor gcd is extended in a logarithmic x, Y after the gcd, a set of solutions is given a, b, such that
a*x+b*y=gcd(x,y)
Easy to see, if y is the modulus, and gcd x and y is 1,
a*x+b*y=1
a * x% y = 1
According to the definition of the inverse, when a mold is inverse element of x y.
int exgcd(int a,int b,int &x,int &y){ if(b==0){ x=1; y=0; return a; } int g=exgcd(b,a%b,x,y); int t=x; x=y; y=t-(a/b)*y; return g; }