Find the Greatest Common Divisor (GCD) of two positive integers
The Euclidean algorithm is based on the simple observation that the GCD of two numbers doesn't change if the smaller number is subtracted from the larger number:
Let
Let
Proof by contradiction that
Assume
If
If
To speed matters up in practice, modulo division is used instead of repeated subtractions:
A straightforward Lua implementation might look as follows:
function gcd(a, b)
while b ~= 0 do
a, b = b, a % b
end
return a
end
note that %
is the modulo/remainder operator;
a
is assigned to the previous value of b
,
and b
is assigned to the previous value of a
modulo the previous value of b
in each step.
The space complexity can trivially be seen to be constant:
Only two numbers (of assumed constant size),
Each iteration of the while loop runs in constant time and at least halves
Finding the GCD of
$42 \mod 12 = 6$ $12 \mod 6 = 0$
The result is
Finding the GCD of
$633 \mod 142 = 65$ $142 \mod 65 = 12$ $65 \mod 12 = 5$ $12 \mod 5 = 2$ $5 \mod 2 = 1$ $2 \mod 1 = 0$
The result is
- Shortening fractions
- Finding the Least Common Multiple (LCM)
- Efficiently checking whether two numbers are co-prime (needed e.g. for the RSA cryptosystem)