求乘法逆元,有多种方法,目前只会扩展欧几里得求逆元:讲解在这
#include<iostream>
using namespace std;
int exgcd(int a,int b,int &x,int &y)
{
if(a == 0 && b == 0)
{
return -1;
}
if(b == 0)
{
x = 1;
y = 0;
return a;
}
int d = exgcd(b,a%b,y,x);
y -= a / b * x;
return d;
}
int inv(int a,int b)
{
int x,y;
int d = exgcd(a,b,x,y);
if(d == 1)
{
return (x % b + b) % b;
}
else
{
return -1;
}
}
int main()
{
int a,b;
while(cin>>a>>b)
{
cout<<inv(a,b)<<endl;
}
}