Pages - Menu

Monday 8 October 2012

Finding the greatest common divisor of two integers in C

The greatest common divisor (gcd), also known as the greatest common factor (gcf) or the highest common factor (hcf) of two or more non-zero integers is the largest positive integers that divides the numbers without a remainder. (wikipedia

Euclidean algorithm using subtraction

/*
 * Description:
 *  Finds the greatest common divisor
 * Parameters:
 *  a - the first number
 *  b - the second number
 * Returns:
 *  gcd - the greatest common divisor of a and b
 */
int GCD(int a, int b)
{
    int gcd = 0;
    if(a < 0)
    {
        a = -a;
    }
    if(b < 0)
    {
        b = -b;
    }
    while (a != b)
    {
        if (a > b)
        {
            a -= b;
        }
        else
        {
            b -= a;
        }
    }
    gcd = a;
    return gcd;
}

Euclidean algorithm using division

/*
 * Description:
 *  Finds the greatest common divisor
 * Parameters:
 *  a - the first number
 *  b - the second number
 * Returns:
 *  gcd - the greatest common divisor of a and b
 */
int GCD(int a, int b)
{
    int gcd = 0, r = a%b;
    if(a < 0)
    {
        a = -a;
    }
    if(b < 0)
    {
        b = -b;
    }
    while (r != 0)
    {
        a = b;
        b = r;
        r = a%b;
    }
    gcd = b;
    return gcd;
}

Recursive algorithm using subtraction

/*
 * Description:
 *  Finds the greatest common divisor using recursion
 * Parameters:
 *  a - the first number
 *  b - the second number
 * Returns:
 *  gcd - the greatest common divisor of a and b
 */
int GCD(int a, int b)
{
    int gcd = 0;
    if(a < 0)
    {
        a = -a;
    }
    if(b < 0)
    {
        b = -b;
    }
    if (a == b)
    {
        gcd = a;
        return gcd;
    }
    else if (a > b)
    {
        return GCD(a-b,b);
    }
    else
    {
        return GCD(a,b-a);
    }
}

Recursive algorithm using division

/*
 * Description:
 *  Finds the greatest common divisor using recursion
 * Parameters:
 *  a - the first number
 *  b - the second number
 * Returns:
 *  gcd - the greatest common divisor of a and b
 */
int GCD(int a, int b)
{
    int gcd = 0;
    if(a < 0)
    {
        a = -a;
    }
    if(b < 0)
    {
        b = -b;
    }
    if (b == 0)
    {
        gcd = a;
        return gcd;
    }
    else
    {
        gcd = GCD(b,a%b);
    }
    return gcd;
}
Example:
#include<stdio.h>
#include<conio.h>

int GCD(int a, int b);

int main(void)
{
    int a = 0, b = 0, gcd = 0;
    printf("\n Enter the first number: ");
    scanf("%d",&a);
    printf(" Enter the second number: ");
    scanf("%d",&b);
    gcd = GCD(a,b);
    printf("\n\tThe greatest common divisor is: %d",gcd);
    getch();
    return 0;
}
Output:  


Read about the gcf of an array of integers in this article.

No comments:

Post a Comment