The Extended Euclidean algorithm is:
Ax + by = gcd (A, B)
Returns an integer (x, y)
1. Non-Recursive Implementation:
First, let's look at the situation where a = 60, B = 22:
The left side of the table is the Euclidean algorithm, and the right side of the equation is used to calculate the solutions of AX + by = gcd (A, B ).
| A = 2 × B + 16 |
16 = A-2b |
| B = 1 × 16 + 6 |
6 = B-1 × 16 = B-1 × (a-2b) =-A + 3B |
| 16 = 2x6 + 4 |
4 = 16-2 × 6 = (A-2b)-2 × (-A + 3b) 3A-8b |
| 6 = 1X4 + 2 |
2 = 6-1X4 = (-A + 3b)-1 × (3A-8b) =-4A + 11b |
| 4 = 2X2 + 0 |
|
This is the pseudocode in number theory guidance:
- Set x = 1, G = A, V = 0 and W = B
- If W = 0, set Y = (G-Ax)/B and return values (G, x, y)
- G divide by W to get the remainder T, G = QW + T
- Set S = x-QV
- Set (x, G) = (V, W)
- Set (V, W) = (S, T)
- Go to step 2
So how is X calculated? X is the coefficient of A in the last remainder minus the obtained Q multiplied by a in the last remainder.
That is, R (n) = R (n-2)-Q (n) × R (n-1) (The number in parentheses represents the subscript)
This sentence is a bit round, = _ = !!..
Let's look at the general table:
| A = q1b + r1 |
R1 = A-q1b |
| B = q2r1 + R2 |
R2 = B-q2r1 |
| R1 = q3r2 + r3 |
R3 = R1-q3r2 |
| ...... |
...... |
1 int ex_gcd1(int a, int b, int &x, int &y) 2 { 3 int g, v, w, s, t, q; 4 x = 1; 5 v = 0; 6 g = a; 7 w = b; 8 while(w != 0) 9 {10 q = g / w;11 t = g % w;12 s = x - q*v;13 x = v;14 g = w;15 v = s;16 w = t;17 }18 y = (g - a*x) / b;19 return g;20 }Code Jun
II. Implementation of Recursion
Make a' = A % B, T = A/B, y' = Y + Tx
Ax + by = G
Ax-tbx + by = G
(A-TB) x + B (Tx + y) = g
A' x + by' = G
By '+ a' x = G
Y = y'-TX, y' is a recursive y that is deeper than Y
1 int ex_gcd2(int a, int b, int &x, int &y) 2 { 3 if(b == 0) 4 { 5 x = 1; 6 y = 0; 7 return a; 8 } 9 int g = ex_gcd2(b, a%b, y, x);10 y = y - a/b*x;11 return g;12 }Code Jun