简体   繁体   中英

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

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))     

Your lcm logic is wrong the condition you used in while loop is wrong. LCM logic should be like,

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))     

Addition to the above answers, you can find LCM of two numbers using GCD. GCD of two numbers take less time when the two numbers are Co prime.First calculate GCD in this way:

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

Then calculate LCM using this formula:

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM