扩展欧几里得算法,简称 exgcd,一般用来求解不定方程,求解线性同余方程,求解模的逆元等
引理:存在 x , y 使得 gcd(a,b)=ax+by
目录
算法原理:
Code:
int exgcd(int a,int b,int &x,int &y) {
if(!b) {
x=1,y=0;
return a;
}
int d=exgcd(b,a%b,y,x);
y-=a/b*x;
return d;
}
应用
1.解线性同余方程
做法:
Code:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int n;
int exgcd(int a,int b,int &x,int &y)
{
if(!b)
{
x=1,y=0;
return a;
}
int d=exgcd(b,a%b,y,x);
y-=a/b*x;
return d;
}
int main()
{
cin>>n;
while(n--)
{
int a,b,m,x,y;
scanf("%d%d%d",&a,&b,&m);
int d=exgcd(a,m,x,y);
if(b%d) puts("impossible");
else
{
int res=(ll)x*b/d%m;
printf("%d\n",res);
}
}
return 0;
}
2.求逆元
当a与b互质时,a在模b意义下有逆元
求法和解线性同余方程一样
Code:
#include<bits/stdc++.h>
using namespace std;
int exgcd(int a,int b,int &x,int &y) {
if(!b) {
x=1,y=0;
return a;
}
int d=exgcd(b,a%b,y,x);
y-=a/b*x;
return d;
}
int main() {
int a,b,x,y;
cin>>a>>b;
exgcd(a,b,x,y);
cout<<(x%b+b)%b; //逆元
}