Python Program to find LCM of two numbers

In this tutorial, we will be going over the simplest yet more efficient program to find the LCM of 2 numbers in Python programming. LCM stands for least Common Multiple.

Knowledge of the following topics will be helpful:

LCM of two Numbers

Least Common Multiple or Lowest Common Multiple abbreviated as LCM is an arithmetic function to find the smallest positive integer that is divisible by both numbers. You can more about it here.

Below is given our Python program to find LCM of 2 numbers:

#LCM function 
def lcm(a, b):  
    if a > b:  
       greater = a  
       greater = b
    counter = greater
        if((counter % a == 0) and (counter % b == 0)):  
           lcm = counter  
        #Incrementing counter by greater
        counter += greater
    return lcm  

#Taking Input from user  
num1 = int(input("Enter first number: "))  
num2 = int(input("Enter second number: "))  
print("The L.C.M. of", num1,"and", num2,"is", lcm(num1, num2))

In the above code we will be finding the LCM of two numbers using a function call. First, we ask the user to input the numbers using int(input(“Enter first number: “)) and int(input(“Enter second number: “)). Here, input() prints the message on the console and also reads the input given as a string. But we want the input to be an int so that we can perform mathematical operations on them and for that we use int().

We then call lcm() with the two user inputted numbers as arguments, i.e. lcm(num1, num2). Inside the lcm() we first find the greater of the two numbers using if…else statements. Following which we initialize counterĀ as the greater number.

Now, we start an infinite while loop. We will come out of it when break statement is called. Inside the while loop we check if counter is divisible by both the numbers, using mod(%) operand. If counter is divisible by both, then counter is the LCM and we break out of the loop. If not then we increment counter by the value of greater, so that counter is a multiple of greater (this works because the lcm has to be a multiple of both the integers).

Once the loop finishes execution, it returns the lcm value and this value is displayed using print()which called the lcm() function.


Enter first number: 5
Enter second number: 7
The L.C.M. of 5 and 7 is 35

So, here it is a simple yet efficient program to find the LCM of 2 numbers.

Also read,

One response to “Python Program to find LCM of two numbers”

  1. maira says:

    really good one … I had never posted comments but your code and your knowledge, your providing style best I request kindly some little project related to image processing also share with us,

Leave a Reply

Your email address will not be published. Required fields are marked *