我的查找 LCM 的功能不起作用。 while循环有问题吗?

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

我的查找LCM的功能不起作用。 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))     

要使您的代码正常工作,最小的更改 是在 while 条件上放置一个 not - 如果两个余数都不为 0.

,您希望循环 重复
while not ((max%x==0) and (max%y==0)):

顺便说一句,您的函数没有 return 值,所以它 implicitly returns Noneprint() 接收的值。在 while-block 之后添加它:

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 是布尔值 Falsey,非零整数和浮点数是布尔值 Truthy,因此 while 检查可以简化为:

while max % x or max % y:

因此,如果任一值(余数)不为零,则循环重复。

提示:max() 是一个 Python 内置变量名,因此不要将其用作变量名。

除了上面的答案,你还可以用GCD求出两个数的LCM。两个数的GCD在两个数是Co的情况下花费的时间更少 prime.First 计算GCD的方法是:

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

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

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