为什么我的C中的GCD程序无法运行? [英] Why is my GCD program in C not running?

查看:485
本文介绍了为什么我的C中的GCD程序无法运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用C中的Euclid算法(递归)找到两个数字的GCD,但我确实知道数学上它并不完全理想,因为它忽略了负数条件,但是我只想让这个数字对正数有效现在.

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

推荐答案

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

这意味着您需要添加一张支票.

That means you need to add a check.

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

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

这篇关于为什么我的C中的GCD程序无法运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆