8000 Update extended-euclid-algorithm.md · cp-algorithms/cp-algorithms@997f7d1 · GitHub
[go: up one dir, main page]

Skip to content

Commit 997f7d1

Browse files
Update extended-euclid-algorithm.md
Added the proof for maintaining the invariants in the iterative algorithm.
1 parent edea689 commit 997f7d1

File tree

1 file changed

+26
-3
lines changed

1 file changed

+26
-3
lines changed

src/algebra/extended-euclid-algorithm.md

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -95,9 +95,32 @@ int gcd(int a, int b, int& x, int& y) {
9595

9696
If you look closely at the variables `a1` and `b1`, you can notice that they take exactly the same values as in the iterative version of the normal [Euclidean algorithm](euclid-algorithm.md). So the algorithm will at least compute the correct GCD.
9797

98-
To see why the algorithm also computes the correct coefficients, you can check that the following invariants will hold at any time (before the while loop, and at the end of each iteration): $x \cdot a + y \cdot b = a_1$ and $x_1 \cdot a + y_1 \cdot b = b_1$.
99-
It's trivial to see, that these two equations are satisfied at the beginning.
100-
And you can check that the update in the loop iteration will still keep those equalities valid.
98+
To see why the algorithm computes the correct coefficients, consider that the following invariants hold at any given time (before the while loop begins and at the end of each iteration):
99+
100+
$$x \cdot a + y \cdot b = a_1$$
101+
102+
$$x_1 \cdot a + y_1 \cdot b = b_1$$
103+
104+
Let the values at the end of an iteration be denoted by a prime ($'$), and assume $q = \frac{a_1}{b_1}$. From the [Euclidean algorithm](euclid-algorithm.md), we have:
105+
106+
$$a_1' = b_1$$
107+
108+
$$b_1' = a_1 - q \cdot b_1$$
109+
110+
For the first invariant to hold, the following should be true:
111+
112+
$$x' \cdot a + y' \cdot b = a_1' = b_1$$
113+
114+
$$x' \cdot a + y' \cdot b = x_1 \cdot a + y_1 \cdot b$$
115+
116+
Similarly for the second invariant, the following should hold:
117+
118+
$$x_1' \cdot a + y_1' \cdot b = a_1 - q \cdot b_1$$
119+
120+
$$x_1' \cdot a + y_1' \cdot b = (x - q \cdot x_1) \cdot a + (y - q \cdot y_1) \cdot b$$
121+
122+
By comparing the coefficients of $a$ and $b$, the update equations for each variable can be derived, ensuring that the invariants are maintained throughout the algorithm.
123+
101124

102125
At the end we know that $a_1$ contains the GCD, so $x \cdot a + y \cdot b = g$.
103126
Which means that we have found the required coefficients.

0 commit comments

Comments
 (0)
0