Python Program to find LCM of two numbers

Find LCM of two numbers in python :

What is a LCM ? LCM or least common multiplier of two number is the smallest number that is divisible by both of these numbers. i.e. the lowest number starting from 1, that is divisible by both.

To find out the LCM of two numbers in python or in any programming language, we can check for each numbers if it is divisible by both or not. Or, we can start this counting from the greater number , that will save us a lot of time.Or, we can only check for the multiplier of the greater number instead.Which method will be the fastest ? Of course the third one.Let’s take a look into the python program :

Program :

def findLcm(a,b):
    large_no = 0
    
    if(a>b):
        large_no = a
    else :
        large_no = b
        
    multiplier = 1
    lcm = large_no
    
    while(lcm < (a*b)):
        print ("checking for ",lcm)
        if(lcm % a == 0 and lcm % b ==0):
            break
            
        multiplier += 1
        lcm = large_no * multiplier
    
    print ("lcm is ",lcm)
    

num1 = 31
num2 = 15

findLcm(num1,num2)

Description :

To get the lcm of two numbers, we need to find the multiplier for both of the numbers. And lowest multiplier will be the LCM. If one number is divisible by the other number, then the greater number will be the LCM.


1. In the above example, we have one method named ‘findLcm’ that takes two numbers as input and print out the LCM for both.
2. First we are checking between these two number which one is greater and saving it to a variable ‘greater_num’
3. Consider the greater number as lcm. If it is divisible by the smaller number, then it will be the lcm for both.
4. Now, inside the while loop, we are checking if the ‘lcm’ is divisible by both the numbers or not. If yes, then print it as the lcm, if not , then change ‘lcm’ to the next multiplier of the greater number. i.e. we are checking for all the multiplier of the greater number .
5. This loop will exit if ‘lcm’ becomes equal to the multiplication of both the numbers.

Try this example with different numbers and let me know if you find any trouble on it.

Leave a Reply