Euclidean Algorithm


One common trick taught in competitive programming is the formula to calculate the greatest common divisor of two numbers. That is, for some integers a and ba \text{ and }b, the largest integer cc such that xa and xbx \mid a \text{ and }x \mid b. The algorithm can be thought of as the following: Given two integers a,ba, b, we can say that

gcd(a,b)=gcd(b,a%b)gcd(a,b)=gcd(b,a\%b)
and

gcd(a,b)=a when b=0gcd(a, b) = a \text{ when b} = 0

The latter follows from the fact that aa is the largest integer to divide itself, and everything divides 0 (because 0=an for any integer a when n=00=an \text{ for any integer $a$ when }n=0 ).

But how do we know this to be true? Well, let’s prove it. Take x=gcd(a,b),y=gcd(b,a%b)x = gcd(a,b), y=gcd(b,a\%b). If we can show that x<=y,y<=xx <= y, y <= x, then we it must be true that x=yx=y, which means the GCDs are indeed equal.

By definition of GCD, xa,xbx \mid a, x \mid b. This means that a=xka=xk for some integer k, and b=xjb=xj for some integer j. To show that x<=yx <= y, we look to first show that x(a%b)x \mid (a\%b), since it already divides b. By definition, a=bq+(a%b)a=bq+(a\%b) for some integer q. Substituting in our earlier definitions for a and b, we get xk=(xj)q+(a%b)xk=(xj)q+(a\%b). Rearranging the equation, we get a%b=xkxjq=x(kjq)a\%b=xk-xjq=x(k-jq). By definition, xx(kjq)x \mid x(k - jq), and so we get that xb,x(a%b)x \mid b, x \mid (a\%b). Because y is their GCD, this means that x<=yx <= y has been established.

Now, we want to show that y<=xy <= x. We will do something similar to the first part, and show that ya,yby \mid a, y \mid b. We’re given that yb,y(a%b)y \mid b, y \mid (a\%b). This give us b=yk,(a%b)=yjb=yk', (a\%b)=yj' for some integers k’, j’. By definition, a=bq+(a%b)a=bq'+(a\%b) for some integer k. With substitutions, we get that a=(yk)q+yj=ykq+yj=y(kq+j)a=(yk')q' + yj'=yk'q' +yj'=y(k'q'+j'). By definition, yy(kq+j)y \mid y(k'q'+j'), and thus y divides a. Since x is the gcd of a and b, and y divides both a and b, it must hold that y<=xy <= x.