Extended Binary Euclidean Algorithm
Core Idea
This code operates as follows:
It removes the common factor 2k from A=2ka and B=2kb.
Then, it applies the Binary GCD rules starting from u=a and v=b, and reduces u and v until they become equal. The case where both u and v are even has already been handled in the previous step, so it's excluded here.
Meanwhile, we set the variables as x1=1,y1=0,x2=0,y2=1, and maintain the following two invariants:
At each step, we update the expressions in a way that preserves these invariants. Let’s consider only case 2 and case 4 as examples.
Case 2: When u is even and v is odd
If x1 and y1 are both even, we update as follows:
Otherwise (if either is odd), we update as:
Why are x1+b and y1−a always even?
Since u is even, the expression ax1+by1 must also be even. A sum is even only if both terms are even or both are odd.
Now, note that a and b cannot both be even — because we already factored out the common power of 2 beforehand.
odd
odd
odd
odd
odd
odd
even
odd
even
odd
even
even
odd
even
even
even
odd
even
In each of these cases, the sum ax1+by1 is even, and both x1+b and y1−a are even as well.
Case 4: When u>v and both u and v are odd
Code
Written by Ryan Kim of Fractalyze
Last updated