Friday, 29 August 2014

Euclid's Algorithm (Greatest Common Divisor)

Following is how to find the greatest common divisor of two positive numbers, m and n, using Euclid's Algorithm.

  1. Divide m by n and let r be the remainder.
  2. If r is 0, n is the answer; if r is not 0, continue to step 3.
  3. Set m = n and n = r. Go back to step 1.
 Below is my implementation of this algorithm.

#include <stdio.h>

int greatestCommonDivisor(int m, int n)
{
    int r;

    /* Check For Proper Input */
    if((m == 0) || (n == 0))
        return 0;
    else if((m < 0) || (n < 0))
        return -1;

    do
    {
        r = m % n;
        if(r == 0)
            break;
        m = n;
        n = r;
    }
    while(true);

    return n;
}

int main(void)
{
    int num1 = 600, num2 = 120;
    int gcd = greatestCommonDivisor(num1, num2); 

    printf("The GCD of %d and %d is %d\n", num1, num2, gcd);

    getchar();
    return 0;
}

No comments: