Euclid out of nowhere proposed this algorithm which calculates the greatest common divisor of two numbers. The simplest way of calculating the GCD is probably the simple prime factorization method. But, Euclid was no common chap. He devised a way which calculates the GCD recursively. The idea was to simplify the problem each time, preserving the GCD. Lets discuss the algorithm, in order to understand it-
getGCD(n, m) {
while(n % m != 0) {
r = n % m;
n = m;
m = r;
}
return m;
}
- The next iteration is always getGCD(m, n % m), the thing to keep in mind here is that the GCD for (n, m) is same as (m, n % m).
- Also note, that sum of the two numbers in each iteration reduces to <= 3/2 of its value. log (m + n) base 3/2. i.e. The sum is bound to 3/2.
Proof of the 3/2 fact -
Let the input be p and q, the input for next iteration be p’ and q’.
here, q’ = p % q <= q
=> p’ = q
=> p’ + q’ = remainder + divisor <= dividend (p)
now, p’ + q’ + (p’ + q’) + (p’ + q’) <= q + q + 2p
=> 3(p’ + q’) <= 2(p + q)
=> (p + q)/(p’ + q’) = 3/2
Hence proved.
I am still confused, how he thought of this algorithm, but hats off to Euclid.
