2017-05-27 151 views

回答

1

在你第一次迭代,a%2等於零(12%2),b%2(24%2)也等於零。

現在你已經加倍count1。然後你用(0, 0)參數lcm(因爲已經建立,12 % 2 == 0 and 24 % 2 == 0)。

接下來我們正在做0 % 2,這等於0。然後這個循環會一直持續下去。

代碼更好的解決方案:

def gcd(x, y): 
    # This is the Euclidian algorithm for getting the highest 
    # common factor (greatest common denominator) of two numbers 
    while y != 0: 
     x, y = y, x % y 
    return x 

def lcm(x, y): 
    lcm = (x*y)//gcd(x,y) 
    return lcm 


print(lcm(12, 24)) 

Source

+0

哇!很高興知道我也可以在不使用GCF的情況下找出LCM.Thanks for the source! –

+0

是的,我是通過LCM(0,0),因此它永遠循環。感謝指出! –

1

這不是真的清楚如何你打算如何實施lcm,但我的理解是

# lowest common multiple 
# where gcd = greatest common divisor 
lcm(m,n) = m * n/gcd(m,n) 

這樣,我們可以實現lcm很容易

def gcd (m,n): 
    if n == 0: 
    return m 
    else: 
    return gcd(n, m % n) 

def lcm (m,n): 
    return m * n/gcd(m,n) 

print(lcm(12,24)) # 24 
+0

嘿非常感謝GCD看起來很好的方式,找出LCM! –

相關問題