Search code examples
crecursionlogicgreatest-common-divisor

Recursive GCD Logic Error


As far as I can tell the logic in this makes sense. Yet the output is incorrect and I can seem to make sense of it.

#include <stdio.h>

int gcd(int, int);

int main()
{
    int n, m;

    printf("enter two numbers");
    scanf("%d%d", &n, &m);

    printf("The gcd of %d and %d is: %d \n", n, m, gcd(n,m));

    return 0;
}

int gcd(int x, int y)
{
    while(x!=y){
           if(x>y)
                    return (x-y,y);

            else
                    return(x,y-x);
    }
    return x;
}

Solution

  • That's not a recursive implementation of gcd, the function is not calling itself and besides it's using a while loop. A truly recursive approach will look like this:

    int gcd(int x, int y) {
        if (y == 0)
            return x;
        else
            return gcd(y, x % y);
    }
    

    Or a bit shorter:

    int gcd(int x, int y) {
        return y == 0 ? x : gcd(y, x % y);
    }
    

    The above implementation is based on the Euclidean algorithm, refer to this for more details.