簡體   English   中英

我的用於查找 LCM 的 function 不起作用。 while循環有問題嗎?

[英]My function for finding LCM does not work. Is there a problem with the while loop?

我的用於查找 LCM 的 function 不起作用。 while循環有問題嗎?

x = int(input("Enter the first number"))
y = int(input("Enter the second number"))
def calculate_LCM(x,y):
    if (x>y):
        max=x
    else:
        max=y
    while((max%x==0) and (max%y==0)):
        print(max)
        max=max+1
          
          
print(calculate_LCM(x,y))     

你的 lcm 邏輯是錯誤的,你在 while 循環中使用的條件是錯誤的。 LCM邏輯應該是這樣的,

def calculate_LCM(x, y):

   # choose the greater number
   if x > y:
       greater = x
   else:
       greater = y

   while(True):
       if((greater % x == 0) and (greater % y == 0)):
           lcm = greater
           break
       greater += 1

   return lcm

x = int(input("Enter the first number"))
y = int(input("Enter the second number"))

print(calculate_LCM(x,y))     

除了上述答案,您還可以使用 GCD 找到兩個數字的 LCM。 當兩個數互質時,兩個數的 GCD 花費的時間更少。首先這樣計算 GCD:

def gcd(a,b):
    if b==0:
        return a
    else:
        return gcd(b,a%b)

然后使用以下公式計算 LCM:

lcm = (a*b)//gcd(a,b)

使您的代碼工作的最小更改是在while條件上放置一個not -如果兩個余數都不為 0,您希望循環重復

while not ((max%x==0) and (max%y==0)):

順便說一句,您的 function 不返回值,因此它隱式返回None這是print()接收的內容。 在 while 塊之后添加它:

while not (max % x == 0 and max % y == 0):  # remove extra parens and add spaces, PEP8
    max += 1  # same as max = max + 1
return max

旁注:由於 0 是布爾假值,非零整數和浮點數是 boolean 真值while因此檢查可以簡化為:

while max % x or max % y:

因此,如果任一值(余數)不為零,則循環重復。

提示: max()是一個 Python 內置所以不要使用它作為變量名。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM