My function for finding LCM does not work. Is there a problem with the while loop?
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))
The smallest change to make your code work is to put a not
on the while
condition - you want the loop to repeat if both remainders are not 0.
while not ((max%x==0) and (max%y==0)):
Btw, your function doesn't return a value, so it implicitly returns None
which is what print()
receives. Add it after the 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
Side note: since 0 is boolean-Falsey and non-zero integers and floats are boolean Truthy, that while
check can be reduced to:
while max % x or max % y:
so if either value (remainders) is non-zero, the loop repeats.
Tip: max()
is a Python built-in so don't use that as a variable name.