Greatest common divisor

The greatest common divisor of two numbers, $$x$$ and $$y$$ is the biggest integer that divides both $$x$$ and $$y$$.

This comes in handy when calculating the least common multiple, since $$lcm(a,b) = \frac{ a b }{ gcd(a,b) }$$.

The gcd can be found by using the Euclidean algorithm:

func gcd( var a as Integer, var b as Integer ) if ( b > 0 ) return gcd( b, a mod b ) return a

Why does this work? The fact we need is that $$gcd(a,b) = gcd(a, b-a)$$. To see why this is true, let $$g = gcd(a,b)$$. Thus $$g$$ divides both $$a$$ and $$b$$, by definition. This means, in turn, that $$a = kg$$ and $$b = mg$$, for some values of $$k$$ and $$m$$. $$b - a = mg - kg = (m - k)g$$, and therefore $$g$$ divides $$b - a$$ as well. This means that $$gcd(a,b) \leq gcd(a, b-a)$$. The inequality going in the other direction is similar, and therefore $$gcd(a,b) = gcd(a, b-a)$$, as desired.

Of course, this process can be iterated. Note that $$gcd(a,b) = gcd(a, b-a) = gcd(a, b-2a) = \ldots$$, and, in particular, $$gcd(a,b) = gcd(a, b \% a)$$, justifying the use of the modulus. The point of the algorithm is to continue this procedure until one number is 0, because $$gcd(0, x) = x$$, which we can then return as our answer.

Assume that the input to the algorithm is such that $$a \leq b$$. Then because the numbers decrease at every step, the runtime is at most $$O(b)$$. In practice, the algorithm typically does much, much better.