Extended Euclidean Algorithm
The original mathematics was not good. When I saw the LRJ mathematical topic, I went online to Baidu to learn how to prove the Extended Euclidean algorithm.
First, let's talk about the simple Euclidean algorithm, that is, the division of the moving phase, which is very simple.
int gcd(int a,int b){ return b == 0 ? a : gcd(b,a % b);}
The following describes how to extend the Euclidean algorithm.
Returns x and y FOR a and B so that a * x + B * y = gcd (a, B );
Let's set a> B, and x> y
Then when B = 0, gcd (a, B) = a, so x = 1, y = 0;
If B! When the value is 0, we know that
Ax1 + by1 = gcd (a, B) = bx2 + (a % B) y2; (according to the simple Euclidean)
Let's simplify this formula.
Ax1 + by1 = bx2 + (a-(a/B) * B) y2;
Ax1 + by1 = bx2 + a * y2-(a/B) * B * y2;
Ax1 + by1 = a * y2 + B * (x2-(a/B) * y2 );
Therefore, x1 = y2;
Y1 = (x2-(a/B) * y2 );
That is to say, the x and y of each layer can be obtained from the x and y of the previous layer, and the recursive endpoint is B = 0;
# Include
# Include
# Include
# Include
# Include
# Include
# Include
# Include
# Include
# Include
# Include
# Include
# Include
Using namespace std; # define _ PI acos (-1.0) # define INF 1 <10 # define esp 1e-6typedef long LL; typedef unsigned long ULL; typedef pair
Pill; /* ===================================================== ========================================================== ========= */void gcd (int, int B, int & d, int & x, int & y) {if (! B) {d = a; x = 1; y = 0;} else {gcd (B, a % B, d, y, x ); y-= x * (a/B) ;}} int main () {int x, y, a, B, c; while (scanf ("% d ", & a, & B )! = EOF) {x = max (a, B); y = x; if (a <B)/* guarantees a> B */swap (a, B ); gcd (a, B, c, x, y);/* represents a * x + B * y = c */printf ("(% d * % d) + (% d * % d) = % d \ n ", a, x, B, y, c);} return 0 ;}