Write a program in python to find LCM of two numbers.

LCM or Least Common Multiple of any two positive integers is the minimum number that is divisible by both the given numbers. Example LCM of 5 and 6 is 30.

There are multiple methods to find lcm in python. Let’s study each of them.

Method 1: Using While Loop

print("Enter two numbers")
a = int(input())
b = int(input())

greater = a if a > b else b 

while(1):
    if(greater%a == 0) and (greater%b == 0):
        break
    greater += 1
    
print("LCM: ",greater)

Output

Enter two numbers                                                                                                             
8                                                                                                                             
9                                                                                                                             
LCM:  72 

This method is not so efficient because we are looping from the greater number to the number which is divisible by both the a and b.

We can efficiently solve lcm in python using gcd.

Method 2: LCM using GCD

For any given two numbers the following relationship holds true.

a * b = LCM * GCD

So we can get LCM using (a*b)/GCD.

Let’s do the same but before that I recommend you to check how to calculate GCD of two numbers in Python.

def findGCD(l, s):
    while(s):
        l, s = s, l%s
    return l
    
print("Enter two numbers")
a = int(input())
b = int(input())

GCD = findGCD(a, b)
LCM = (a*b)/GCD
    
print("LCM: ",LCM)

Output

Enter two numbers                                                                                                             
12                                                                                                                            
4                                                                                                                             
LCM:  12.0

In the above method we are first calculating GCD of two numbers using Euclidean Algorithm, then we put the value of the same into the formula LCM = (a*b)/GCD to compute the LCM of the a and b.

If you have any doubts or suggestion then comment below.

Leave a Reply