Search code examples
calgorithmfunctionrecursiongreatest-common-divisor

Why is my GCD program in C not running?


I am trying to find the GCD of two numbers using Euclid's algorithm in C (recursively) and I do know that mathematically it's not completely perfect yet as it neglects negative number conditions, but I just want this one to work for positive numbers for now.

#include <stdio.h>

int gcd(int m, int n);

int main() {
    return gcd(60, 24);
}

int gcd(int m, int n) {
    if (m < n) {
        //swapping both a and b
        m = m + n;
        n = m - n;
        m = m - n;
    }
    if (m == n) {
        return m;
    } else {
        return gcd(n, m % n);   
    }
}

Solution

  • gcd(60, 24) -> gcd(24, 12) -> gcd(12, 0).

    That means you need to add a check.

    if ( n == 0 )
    {
       return m;
    }
    

    or

    if ( m%n == 0 )
    {
       return n;
    }
    

    You can also remove the variable swapping code with another call to the function with the values swapped in the call.

    int gcd(int m, int n) {
    
       if (m < n) {
          return gcd(n, m);
       }
    
       if (m%n == 0) {
          return n;
       } else {
          return gcd(n, m % n);   
       }
    }