寻找两个数的最大公约数

问题描述

我想在两个输入数字之间找到最大的公约数,我遇到了一个问题。

我不确定我用来实际找到除数的方法是否正确。我通过将两个数字除以每个数字直到数字到达自身来做到这一点。

#include <iostream>
#include <string>

using namespace std;
    
int main() {

    int num1,num2;
    int large = 0;
    int gcd = 0;

    cout << "this program finds the greatest common divisor" << endl;
    cout << "input first  number > "; cin >> num1; 
    cout << "input second number > "; cin >> num2;

    if (num1 > num2)
        large = num1;
    else
        large = num2;

    cout << "larger number  > " << large << endl;
    cout << endl;

    for (int i = 0; i < large + 1; i++) {
        if (num1 % i == 0 && num2 % i == 0) {
            gcd = i;
        }
    }

    cout << "The gcd of " << num1 << " and " << num2 << " is " << gcd << endl;
    cout << endl;
}

解决方法

是的,这很有道理。 基本上,它可以完成工作。您可以做一些不必要的事情。启动循环:

for (int i = 0; i < large + 1; i++)

当i = 1时,因为您不能将其除以0。当i在大数和小数之间时,您还将执行不必要的模运算。 Ofc可以进行很多优化。显然,在较小的数字/ 2到较小的数字上,您也找不到通用的除数(不包括边界数字),并且比较早的较小的数字/ 3到较小的/ 2(-#-)。但是逻辑似乎很可靠:循环中最后找到的除数将是最大的通用除数。

,

您需要进行一些修改才能使其正确。
首先,检查其中一个是否为零,如果为零,则返回另一个。
其次,如果这种情况没有发生,请从1开始,除以0,然后除以最小,而不是最大。

int gcd,small;
if (num1 == 0)
    gcd = num2;
else if (num2 == 0)
    gcd = num1;
else
{
    if (num1 < num2)
        small = num1;
    else
        small = num2;
    for (gcd = 1; gcd < small + 1; gcd++)
        if (num1 % gcd == 0 && num2 % gcd == 0)
            break;
}
cout << "The gcd of " << num1 << " and " << num2 << " is " << gcd << endl;

但是您现在应该拥有更简便,更快捷的方式,例如my answer to this question