Extended Binary Euclidean Algorithm

Core Idea

This code operates as follows:

  1. It removes the common factor 2k2^k from A=2kaA = 2^k a and B=2kbB = 2^k b.

  2. Then, it applies the Binary GCD rules starting from u=au = a and v=bv = b, and reduces uu and vv until they become equal. The case where both uu and vv are even has already been handled in the previous step, so it's excluded here.

gcd(u,v)={gcd(u,v) if u=vgcd(u2,v) if u0(mod2) v1(mod2)gcd(u,v2) if u1(mod2) v0(mod2)gcd(uv,v) if u>vu1(mod2) v1(mod2)gcd(u,vu) if v>uu1(mod2) v1(mod2)\gcd(u, v) = \begin{cases} \gcd(u, v) & \text{ if } u = v\\ \gcd \left(\frac{u}{2}, v \right) & \text{ if } u \equiv 0 \pmod 2 \land \ v \equiv 1 \pmod 2 \\ \gcd \left(u, \frac{v}{2} \right) & \text{ if } u \equiv 1 \pmod 2 \land \ v \equiv 0 \pmod 2 \\ \gcd \left(u - v, v \right) & \text{ if } u > v \land u \equiv 1 \pmod 2 \land \ v \equiv 1 \pmod 2 \\ \gcd \left(u, v - u \right) & \text{ if } v > u \land u \equiv 1 \pmod 2 \land \ v \equiv 1 \pmod 2 \\ \end{cases}

Meanwhile, we set the variables as x1=1,y1=0,x2=0,y2=1x_1 = 1, y_1 = 0, x_2 = 0, y_2 = 1, and maintain the following two invariants:

ax1+by1=u,ax2+by2=vax_1 + by_1 = u, \quad ax_2 + by_2 = v

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 uu is even and vv is odd

If x1x_1 and y1y_1 are both even, we update as follows:

ax1+by1=uax12+by12=u2ax_1 + by_1 = u \Leftrightarrow a\frac{x_1}{2} + b\frac{y_1}{2} = \frac{u}{2}

Otherwise (if either is odd), we update as:

ax1+by1=ua(x1+b)2+b(y1a)2=u2ax_1 + by_1 = u \Leftrightarrow a\frac{(x_1 + b)}{2} + b\frac{(y_1 - a)}{2} = \frac{u}{2}

Why are x1+bx_1 + b and y1ay_1 - a always even?

Since uu is even, the expression ax1+by1a x_1 + b y_1​ must also be even. A sum is even only if both terms are even or both are odd.

Now, note that aa and bb cannot both be even — because we already factored out the common power of 2 beforehand.

a
x₁
a * x₁
b
y₁
b * y₁

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+by1a x_1 + b y_1 is even, and both x1+bx_1 + b and y1ay_1 - a are even as well.

Case 4: When u>vu > v and both uu and vv are odd

ax1+by1=u,ax2+by2=va(x1x2)+b(y1y2)=uvax_1 + by_1 = u,\quad ax_2 + by_2 = v \Leftrightarrow a(x_1 - x_2) + b(y_1 - y_2) = u - v

Code

Written by Ryan Kim of Fractalyze

Last updated