简体   繁体   English

找出两个数的最大公约数

[英]Finding the greatest common divisor of two numbers

I want to find the greatest common divisor between two input numbers, and I bumped into a problem.我想找到两个输入数字之间的最大公约数,但遇到了一个问题。

I am not sure if the method I used to actually find the divisor is right.我不确定我用来实际找到除数的方法是否正确。 I did it by dividing both of the numbers with every number until the number reaches itself.我通过将两个数字除以每个数字来做到这一点,直到数字达到它本身。

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

Yes it makes sense.是的,这是有道理的。 Basically it does the job.基本上它完成了工作。 You do few things unnecessary.你做一些不必要的事情。 Start loop:开始循环:

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

with i=1, as you cant div by 0. Also you are performing unnecessary modulo operations when i is between larger and smaller number. i=1,因为你不能除以 0。当 i 介于较大和较小的数字之间时,你也在执行不必要的模运算。 Ofc it can be optimized a lot. Ofc它可以优化很多。 Obviously on numbers smaller/2 up to smaller you also cant find common divisor(excluding border numbers), and than earlier smaller/3 to smaller/2(-#-).显然,对于更小/2 到更小的数字,您也找不到公约数(不包括边界数字),并且比之前的更小/3 到更小/2(-#-)。 However logic seems solid: last found divisor by the loop will be the gratest common divisor.然而,逻辑似乎很可靠:循环最后找到的除数将是最大公约数。

You need some modifications to make it correct.您需要进行一些修改以使其正确。
First, check whether one of them is zero, if so, return the other.首先,检查其中一个是否为零,如果是,则返回另一个。
Second, if this didn't happen, start dividing from 1, not zero, up to the smallest, not the largest.其次,如果这没有发生,则从 1(而不是零)开始除以最小的,而不是最大的。

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;

But you should now that there are easier and faster ways, like my answer to this question .但是你现在应该有更简单快捷的方法,就像我对这个问题的回答

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM