欧几里得算法:gcd(a,b)=gcd(b,a%b)
求 ax + by = c 的解
gcd(a,b)= c*n否则无解
对于ax+by=gcd(a,b)
当 b=0 时 gcd(a,b)=a
必有解x=1 y=0
假设ax1+by1=gcd(a,b)
根据扩展欧几里得
gcd(a,b)=gcd(b,a%b)=bx2+(a%b)y2 =ax1+by1
所以 ax1+by1=bx2+(a-a/b*b)y2
ax1+by1=ay2+b*(x2-a/b*y2)
所以x1=y2
y1=x2-a/b*y2
#include <iostream> #include <cstdio> using namespace std; void exgcd(long long a,long long b,long long& x,long long& y){ if(b==0){x=1; y=0;} else{exgcd(b,a%b,y,x); y-=a/b*x;} } int main(){ long long a,b,x,y; scanf("%lld%lld",&a,&b); exgcd(a,b,x,y); printf("%lld ",(x+b)%b); return 0; }