定理:如果a和m互质,并且m > 1,那么a模m的逆元存在。且逆元在模m的完全剩余系中唯一。
证明:根据贝祖定理,gcd (a, m) = 1, 存在正数 s 和 t 满足等式
sa+tm = 1,那么sa+tm ≡ 1 (mod m), 又因为 tm ≡ 0 (mod m),
我们利用扩展欧几里德定理,容易找出逆元的存在
void exgcd(int a,int b,int &x,int &y)
{
int t;
if (!b)
{
x = 1;
y = 0;
return;
}
exgcd(b, a%b, x, y);
t = x;
x = y;
y = t - a/b*y;
}
int inverse(int a,int b)
{
int x, y;
exgcd(a, b, x, y);
if (b < 0)
b = -b;
x = x % b;
if (x < 0)
x += b;
return x;
}
x就是最小的正逆元