This algorithm is used to calculate the integers x and y that meet the following conditions:
D = gcd (a, B) = AX + by (D is the maximum approximate number of A and B)
Pseudocode provided in the introduction to algorithms:
Extended_euclid (A, B)
1 If B = 0
2 Return (A, 1, 0)
3 else (D1, X1, Y1) = extended_euclid (B, A mod B)
4 (D, x, y) = (D2, Y1, Y1-(A/B) * Y1)
5 return (D, x, y)
The fourth line is the key.
It does not matter if you cannot understand it. The derivation process is as follows:
Gcd (a, B) = gcd (B, A % B), both of which are in type 1, with AX + by = B * X1 + (a % B) * Y1.
Because I % J = I-(I/J) * J, the right side can be deformed as follows:
B * X1 + (a % B) * Y1 = B * X1 + (a-(A/B) * B) * Y1 = A * Y1 + B * (x1-(A/B) * Y1 ), the final result is AX + by = A * Y1 + B * (x1-(A/B) * Y1)
That is to say, the X of the previous depth is equal to the Y1 of the next depth, and the Y of the previous depth is equal to the x1-(A/B) * Y1 OF THE NEXT depth. Note that the Division used in the above derivation is integer division.
Example:
Question link: http://acm.nyist.net/JudgeOnline/problem.php? PID = 1, 775
Idea: Install Code directly to facilitate understanding.
# Include <iostream> # include <cstdio> using namespace STD; int X, Y, D; // D indicates the maximum public approx. Void extend_gcd (int A, int B) {int T; // records the current x value, because if (B = 0) {x = 1; y = 0; D = A;} is used to calculate y ;} else {extend_gcd (B, A % B); t = x; X = y; y = T-(A/B) * y ;}} int main () {int A, B; while (scanf ("% d", & A, & B )! = EOF) {extend_gcd (a, B); printf ("% d \ n", x, y);} return 0 ;}
References: http://www.cnblogs.com/ka200812/archive/2011/09/02/2164404.html
Extended Forms of Euclidean Algorithms