ThisSiteSucks
ThisSiteSucks

Reputation: 145

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);   
    }
}

Upvotes: 1

Views: 276

Answers (2)

user3386109
user3386109

Reputation: 34839

The code for a recursive GCD looks like this

int gcd(int m, int n)
{
    if (n==0)
        return m;

    return gcd(n, m % n);
}

There is no need to swap arguments, since that will be taken care of by the recursion. For example, consider gcd(24, 60). In this case n=60 and m % n = 24%60 = 24. So the recursive call is gcd(60,24), swapping the arguments automatically.

Upvotes: 7

R Sahu
R Sahu

Reputation: 206687

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);   
   }
}

Upvotes: 4

Related Questions