C++程序计算最大公约数

use*_*141 6 c++ function greatest-common-divisor

我已经启动了这个程序来计算最大的公约数.这是我到目前为止:

#include <iostream>
#include <math.h>
using namespace std;
int getGCD(int a, int b)
{
    a = a % b;
    if (a == 0)
    {
        return b;
        b = b % a;
    }
    if (b == 0)
    {
        return a;
    }
}
int main()

{
    int x, y;
    cout << "Please enter two integers x and y, for GCD calculation" << endl;
    cin >> x >> y;
    cout << "The GCD of " << x << "and " << y << " is" << getGCD(x, y) << endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我总是得到一个0的GCD.我究竟做错了什么?

Jam*_*ack 2

您应该循环查找这一点,如果您使用一些方程来说明其如何工作的算法,这可能会有所帮助。

但是我看到你有两个问题,除非你在另一个循环内调用它。

在两种情况下(无论是 if 还是 else)都会返回,因此您只经过这里一次。

另外,这部分没有意义,为什么b在执行 a 后修改值return

          return b;

          b = b%a;
Run Code Online (Sandbox Code Playgroud)

顺便说一句,您应该为此使用递归。

http://rosettacode.org/wiki/Greatest_common_divisor#Recursive_Euclid_algorithm

  • 不应为此使用递归。找到 GCD 的迭代对于欧几里得来说已经足够好了(*《几何原本》* 大约公元前 300 年,第七卷,命题 1 和 2),对你来说也足够好了。 (2认同)