Why is my GCD program in C not running?

拟墨画扇 提交于 2021-01-06 03:24:25

问题


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

回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/35095965/why-is-my-gcd-program-in-c-not-running

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!