简体   繁体   English

两个数之间的最大公约数,返回最大数

[英]Greatest Common Divisor between two numbers, returning the greatest number

I'm trying to find the Greatest Common Divisor between two numbers.我试图找到两个数字之间的最大公约数。 My test numbers are 45 and 81. While the gcd is 9, it is only returning 3 which is a divisor but it wont move on to return 9. I am close but I can't think of a way to make it return the higher number.我的测试数字是 45 和 81。虽然 gcd 是 9,但它只返回 3,这是一个除数,但它不会继续返回 9。我很接近,但我想不出办法让它返回更高的值数字。

def GCD(num1,num2):
    for i in range(2,num1+1 and num2+1):
        if(num1%i==0 and num2%i==0):
            print("The Greatest Common Denominator between", num1,"and", num2, "is ", end="")
                return i

gcd is a built in function, you can simply do gcd 是一个内置函数,你可以简单地做

from fractions import gcd
gcd(45,81)

That being said, I'll still explain what your error is, as it's good to understand.话虽如此,我仍然会解释您的错误是什么,因为很好理解。 The problem is you return after finding the first common denominator, which breaks the loop so you never get to test 9. A solution is so go through the range from largest to smallest, just reverse it with [::-1] .问题是您在找到第一个公分母后返回,这打破了循环,因此您永远无法测试 9。解决方案是遍历从最大到最小的范围,只需使用[::-1]反转它。 Also, print and return should have the same indentation level.此外, printreturn应该具有相同的缩进级别。

def GCD(num1,num2):
    for i in range(2,num1+1 and num2+1)[::-1]:
        if(num1%i==0 and num2%i==0):
            print("The Greatest Common Denominator between {0} and {1} is {2}".format(num1,num2,i), end="")
            return i

Also, technically % is an obsolete way to put variables in a string, and format() is now recommended此外,从技术上讲%是将变量放入字符串的过时方法,现在推荐使用format()

#include #包括

using namespace std;使用命名空间标准;

int main() { int main() {

int r0, r1,sup2;

cout << "input number one : ";
cin >> r0;

cout << "input number two: ";
cin >> r1;

if (r1 > r0) {

    r1 = r1 + r0;
    r0 = r1 - r0;
    r1 = r1 - r0;
}

while (r1 != 0)
{
    sup2 = r0 % r1;
    r0 = r1;
    r1 = sup2;
}

cout << "\n\nGCD = " << r0 <<endl ;

} }

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

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