find out the lcm of 2 numbers using Python

Viewed 157
def calculate_lcm(x, y):
    if x > y:
        greater = x
    else:
        greater = y
    while (True):
        if ((greater == x == 0) and (greater == y == 0)):
            lcm = greater
            break
        greater += 1


num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
# printing the result for the users  
print("The L.C.M. of", num1, "and", num2, "is", calculate_lcm(num1, num2))

I am getting error please help me.

3 Answers
# defining a function to calculate LCM  
def calculate_lcm(x, y):  
    # selecting 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    
  
# taking input from users  
num1 = int(input("Enter first number: "))  
num2 = int(input("Enter second number: "))  
# printing the result for the users  
print("The L.C.M. of", num1,"and", num2,"is", calculate_lcm(num1, num2)) 

Not sure but it might help and this question is repeated many times.

Please Try My Code and If Get Any Error Then Comment

# defining a function to calculate LCM  
def calculate_lcm(x, y):  
    l = [x,y]
    lesser = min(l)
    greater = max(l)
    if greater % lesser ==0:
        return(greater)
    else:
        i = 1
        while True:
            if (greater*i)%lesser == 0:
                return(greater*i)
            elif i > 100:
                return(greater*lesser)
            i+=1
      
  
# taking input from users  
num1 = int(input("Enter first number: "))  
num2 = int(input("Enter second number: "))  
# printing the result for the users  
print("The L.C.M. of", num1,"and", num2,"is", calculate_lcm(num1, num2)) 

Here is another approach using GCD by implementing Euclidean algorithm.

# Function for calculating GCD 
def calc_gcd(x, y):

   while(y):
       x, y = y, x % y
   return x

# Function for calculating LCM 
def calc_lcm(x, y):
   lcm = (x*y)//calc_gcd(x,y)
   return lcm

# taking input from users  
num1 = int(input("Enter first number: "))  
num2 = int(input("Enter second number: "))  
# printing the result for the users  
print("The L.C.M. of", num1,"and", num2,"is", calc_lcm(num1, num2)) 
Related