Python Program to Find the LCM of two numbers (3 Ways)

In this program, we will learn how to find the LCM of two numbers using the Python programming language.

What is LCM?

it stands for Least Common Multiple. It can be found for two or more numbers by making multiple of the numbers and then choosing the least common multiple.

Let’s take the example of 3 and 4.
Multiple of 3 : 3, 6, 9, 12, 15, 18, 21, 24,…….
Multiple of 4 : 4, 8, 12, 16, 20, 24, 28,…..
So, common multiple of 3 and 4 is 12, 24 and Least Common Multiple is 12.
Hence, LCM of 3 and 4 is 12.

We will discuss three ways to write code for it.

  • Using the loop
  • Using the GCD or HCF
  • Using the Recursion

Python Programming Code to Find the LCM of two numbers

Using the loop

Code:-

num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))

lcm = num1 if(num1 > num2) else num2

while(True):
    if((lcm % num1 == 0) and (lcm % num2 == 0)):
        print("The L.C.M. of", num1,"and", num2,"is", lcm)
        break
    lcm += 1

Ouput:-

Enter first number: 18
Enter second number: 24
The L.C.M. of 18 and 24 is 72

Using the GCD or HCF

Code:-

def gcd(num1,num2):
    if num1%num2 == 0:
        # Base case
        return num2
    else:
        # Iterative case
        return gcd(num2,num1%num2)

num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))

lcm = (num1*num2)//gcd(num1,num2)

print("The L.C.M. of", num1,"and", num2,"is", lcm)

Output:-

Enter first number: 6
Enter second number: 9
The L.C.M. of 6 and 9 is 18

Using the Recursion

Code:-

def lcm(x, y):
    lcm.multiple += y

    if((lcm.multiple % x == 0) and (lcm.multiple % y == 0)):
        return lcm.multiple
    else:
        return lcm(x, y)

lcm.multiple = 0
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))

if num1 > num2:
    lcm = lcm(num2, num1)
else:
    lcm = lcm(num1, num2)

print("The L.C.M. of", num1,"and", num2,"is", lcm)

Output:-

Enter first number: 65
Enter second number: 55
The L.C.M. of 65 and 55 is 715

You can learn about many other Python Programs Here.

Best Books for learning Python with Data Structure, Algorithms, Machine learning and Data Science.

The following two tabs change content below.
Amit Rawat

Amit Rawat

Founder and Developer at SpiderLabWeb
I love to work on new projects and also work on my ideas. My main field of interest is Web Development.

You may also like...