给定两个不等于0的整数M和N,求M和N的最大公约数。
def maxCommonDivisor(m, n): if m == 1 or n == 1 or m == n: return m #调整m,n的顺序使得m<n if m > n: m, n = n, m if n % m == 0: return m for i in range(1, m): if m % i == 0 and n % i == 0: commonDivisor = i return commonDivisor m, n = map(int, input().split()) print(maxCommonDivisor(m, n))
def maxCommonDivisor(m, n): #辗转相除法 #调整m,n的顺序使得m<n if m > n: m, n = n, m if n % m == 0: return m else: return maxCommonDivisor(m, n%m) m, n = map(int, input().split()) print(maxCommonDivisor(m, n))调整m,n的顺序使用系统函数sorted,会大幅度节省运行的空间
m, n = sorted([m, n])