Greatest Common Divisor: Euclid Style

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;

  1. 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).
  2. 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.


About Gaurav

I'm Gaurav; friends call me Teddy, n i'm shivi fr my family!! A java enthusiast who likes experimenting with what he knows. View all posts by Gaurav

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: