简体   繁体   中英

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.

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

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] . Also, print and return should have the same indentation level.

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

#include

using namespace std;

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 ;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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