简体   繁体   中英

Greatest Common Divisor (GCD)

def get_divs(z):
      return [i for i in range(1, z) if z % i == 0]

def gcd(x, y):
      x_div=get_divs(x)
      y_div=get_divs(y)
      cd=set(x_div).intersection(y_div)
      gcd=cd[-1]
      print("The GCD of",x,"and",y,"is",gcd)
      return 1

I'm trying to get this program to compute the Greatest Common Divisor (GCD) of two user-entered, positive integers(x, and y). The set function doesn't return a list that can be indexed. Any suggestions as to how I can find the GCD?

Sorry for replying after 5 years. But you can find GCD by using Euclidean algorithm. And this is the code:

a = int(input('Enter 1st number: '))
b = int(input('Enter 2nd number: '))
r = a%b
while (r!=0):
    a=b
    b=r
    r = a%b
print(f'greatest common divisor is {b}')

Here is what the algo should look like.

findGCD(int firstNum, int secondNum){
int smaller; int bigger;int remainder;
if(firstNum < secondNum) {
    smaller = firstNum;
    bigger = secondNum;
}  
else {
    smaller =  secondNum;
    bigger = firstNum;
}

while(true) {
    remainder = bigger % smaller;
    if(remainder == 0) {
         break;
    }
    else {
         bigger = smaller;
         smaller = remainder;
    }
}
return smaller;
}

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