简体   繁体   中英

Why don't this return the "mrcf" value?

m = int(input('Enter value of m : \t'))
n = int(input('Enter the value of n : \t'))
def GCD(m, n):
 for i in range(1,min(m,n)+1):
  if (m % i) == 0  and (n % i) == 0:
    mrcf = i
  return (mrcf)

This isn't returning anything. Why? - btb. I just started Py, and I'm already lovin this language :)

If I understand the intent of this function GCD, you're potentially updating mrcf multiple times, not just returning the first occurence of (m % i) == 0 and (n % i) == 0 :

m = int(input('Enter value of m : \t'))
n = int(input('Enter the value of n : \t'))

def GCD(m, n):
  for i in range(min(m,n), 1, -1):
    if (m % i) == 0  and (n % i) == 0:
      return i
  return 1

print(GCD(m, n))

UPDATE: as @Barmar suggested, reversing the loop is more efficient

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