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

C++ program to calculate greatest common divisor

本文关键字:最大公约数 计算 程序 c++      更新时间:2023-10-16

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

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

我总是得到0的GCD。我做错了什么?

你应该通过循环找到这个,如果你用一些方程,你的算法应该如何工作,它可能会有所帮助。

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

在两种情况下都返回,要么是if,要么是else,所以这里只遍历一次。

同样,这部分也没有意义,为什么在做了return之后还要修改b的值呢?

          return b;
          b = b%a;

你应该使用递归,顺便说一下。

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

int getGCD(int a, int b) {

//这里我们需要检查b == 0是否返回a

    if (b == 0) {
        return a;
    }
    return gcd(b, a % b);
}

欧几里德算法实现