Extended gcd algorithm
God tm × degree search for exgcd When you hit exg, the ex curry stick comes out. . .
A solution to the spherical equation \(ax+by=\gcd(a,b)\)
If \(b=0\) , then \(\gcd(a,b)=a\) , just take \(x=1,y=0\)
Otherwise: obviously \(\gcd(a,b)=\gcd(b,a\mod b)\)
Then you can recursively solve the solution of \(bx+(a\mod b)y=\gcd(a,b)\) .
Then it is still necessary to push the current \(x,y\) .
设\(bx+(a\mod b)y=\gcd(a,b)\)的解为\(x_0,y_0\),
\(ax+by=\gcd(a,b)=bx_0+(a\mod b)y_0\)
\(=bx_0+ay_0-b\lfloor\frac{a}{b}\rfloor y_0\)
\(=ay_0+b(x_0-\lfloor\frac{a}{b}\rfloor y_0)\)
那么\(x=y_0,y=x_0-\lfloor\frac{a}{b}\rfloor y_0\)
Core code: exgcd(a,b,&x,&y)
return \(\gcd(a,b)\)
il ll exgcd(ll a,ll b,ll&x,ll&y){
ll ret;
if(b==0)x=1,y=0,ret=a;
else{
ret=exgcd(b,a%b,x,y);
ll x0=x,y0=y;
x=y0,y=x0-a/b*y0;
}
return ret;
}
A little extension: the integer solution of the sphere \(ax+by=c\) .
First solve \(ax+by=\gcd(a,b)\) , then if \(c\) is a multiple of \(\gcd(a,b)\) , there will be a solution (multiply both sides of the equation at the same time. ) otherwise no solution (obviously)
Example: poj1061clamfrog date
stay in the pit