There must be an integer pair (x, y) such that ax+by=gcd(a,b)
solves ax+by=gcd(a,b)
After one recursion,
bx1+(a%b)y1=gcd(a,b)
Here we have One point: a%b=a-(a/b)*b into the above formula to get
ay1+b(x1-(a/b)*y1)=gcd(a,b)
so ax+by=ay1+b( x1-(a/b)*y1)
so x=y1; y=x1-(a/b)*y1;
Code:
On the surface, the code I have here looks different from the formula for x and y that I pushed down above, but the careful experience is the same because I swap x and y when I recurse
int extgcd(ll a,ll b,ll &x,ll &y)
{
ll d=a;
if(b!=0)
{
d=extgcd(b,a%b,y,x); //把这里的x,y看做x1,y1。这里就相当于直接给x1赋值y,而y1就等于x
y-=(a/b)*x;
}
else
{
x=1; y=0;
}
return d;
}