Extended Euclidean algorithm uses
When we know $a,b$
Extended Euclidean algorithm can find a $ (x, y) $ solution that satisfies $a*x+b*y=gcd (A, b) $
$GCD (A, b) $ represents $a,b$ greatest common divisor
Preamble Knowledge
$GCD (A, B) =gcd (B,A\%B) $
$GCD (a,0) =0$
$a \%b=a-a/b*b$
Derivation Process
Actually, it's natural to extend Euclid's derivation process.
$a *x+b*y$
$=GCD (A, b) $
$=GCD (b,a\%b) $
$=b*x+ (a\%b) *y$
$=b*x+ (a-a/b*b) *y$
$=b*x+a*y-a/b*b*y$
$=a*y+b*x-a/b*b*y$
$=a*y+ (x-y*a/b) *b$
It's going to go on and on.
When $b=0$
$x =1,y=0$
Code
Attention:
We need to use the $x$ on the previous level when we are asking for $ (x-y*a/b) $
But at this point the previous layer of $x$ has been assigned to $y$
So we need to open an intermediate variable to record the $x$ on the previous layer.
int exgcd (int a,int b,int &x,int &y) { if (b==0) { x=1,y=0; return A; } int R=EXGCD (b,a%b,x,y), TMP; Tmp=x,x=y,y=tmp-a/b*y; return r;}
Application 1
The most important application of expanding Euclid is to find the solution of the shape as $a*x+b*y=c$
So how do you ask for it?
First of all, this equation is capable of $c\%gcd (A, B) =0$, which should be more obvious
According to the extended Euclidean algorithm that was previously
We can first find out the solution of $A*X_0+B*Y_0=GCD (A, b) $ $x_0,y_0$
Then divide both sides of the equation by $GCD (A, b) $
The solution of $A*X_0/GCD (A, B) +b*y_0/gcd (A, B) =1$ is obtained.
and multiply $c$ on both sides of the equation.
We get the equation.
$a *x_0/gcd (A, B) *c+b*y_0/gcd (A, b) *c=c$
Isn't it simple?
2
If $GCD (A, B) =1$, and $x0,y0$ is a group of solutions for $a*x+b*y=c$, then any one solution of the equation can be expressed as
$x =x_0+b*t,y=y_0-a*t$
Prove:
$a *x+b*y$
$=a* (x_0+b*t) +b* (y_0-a*t) $
$=a*x_0+a*b*t+b*y_0-a*b*t$
$=a*x_0+b*y_0$
Examples
Rokua P1516 The frog's date
The equations are listed according to the topic requirements, simplifying can be
Exercises
Extended Euclidean algorithm