Euclid's algorithm starts a sequence with a and b and proceeds by doing modular reductions on consecutive terms of the sequence until zero in reached.
Let the sequence begin with x0=a and x1=b. At any time, let xk=ska+tkb. So, s0=t1=1, and s1=t0=0.
The next term of the sequence is given by xk=xk−2modxk−1. Let qk=⌊xk−1xk−2⌋.
Then, xk=xk−2−qkxk−1, sk=sk−2−qksk−1, and tk=tk−2−qktk−1.
We have to stop wjem xk=0, at which time gcd(a,b)=xk−1. But here we know more: xk−1=sk−1a+tk−1b.
If gcd(a,b)=1 then xk−1=1, and this formula allows us to compute easily.
a−1modb=sk−1modb and
b−1moda=tk−1moda
Example