The Extended Euclid's Algorithm

Euclid's algorithm starts a sequence with aa and bb and proceeds by doing modular reductions on consecutive terms of the sequence until zero in reached.

Let the sequence begin with x0=ax_0 = a and x1=bx_1 = b. At any time, let xk=ska+tkbx_k = s_ka + t_kb. So, s0=t1=1s_0 = t_1 = 1, and s1=t0=0s_1 = t_0 = 0.

The next term of the sequence is given by xk=xk2modxk1x_k = x_{k-2} mod x_{k-1}. Let qk=xk2xk1q_k = \lfloor \frac{x_{k-2}}{x_{k-1}} \rfloor.

Then, xk=xk2qkxk1x_k = x_{k-2} - q_kx_{k-1}, sk=sk2qksk1s_k = s_{k-2} - q_ks_{k-1}, and tk=tk2qktk1t_k = t_{k-2} - q_kt_{k-1}.

We have to stop wjem xk=0x_k = 0, at which time gcd(a,b)=xk1gcd(a,b) = x_{k-1}. But here we know more: xk1=sk1a+tk1bx_{k-1} = s_{k-1}a + t_{k-1}b.

If gcd(a,b)=1gcd(a,b) = 1 then xk1=1x_{k-1} = 1, and this formula allows us to compute easily.

  • a1modb=sk1modba^{-1} mod b = s_{k-1} mod b and

  • b1moda=tk1modab^{-1}mod a = t_{k-1} mod a

Example

Last updated