Write a Python Program to Find LCM

Last Updated on 16 March 2025

The Least Common Multiple (LCM) of two numbers is the smallest positive integer that is divisible by both numbers.

For example, the LCM of 4 and 6 is 12 because 12 is the smallest number that is divisible by both 4 and 6.

In this tutorial, we will write a Python program to find the LCM of two numbers using different methods.

Method 1: Using a Loop (Basic Approach)

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

# Finding the maximum number between the two
max_num = max(num1, num2)

# Loop until we find the LCM
while True:
    if max_num % num1 == 0 and max_num % num2 == 0:
        lcm = max_num
        break
    max_num += 1

# Printing the result
print("LCM of", num1, "and", num2, "is:", lcm)

Output

Enter first number: 5
Enter second number: 15
LCM of 5 and 15 is: 15

Method 2: Using GCD (Efficient Approach)

The LCM can be found using the Greatest Common Divisor (GCD) with this formula:

\[\text{lcm}(a, b) = \frac{|a \times b|}{\gcd(a, b)}\]
import math

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

# Using GCD formula to find LCM
lcm = abs(num1 * num2) // math.gcd(num1, num2)

# Printing the result
print("LCM of", num1, "and", num2, "is:", lcm)

Output

Enter first number: 12
Enter second number: 18
LCM of 12 and 18 is: 36

Method 3: Using a Function (Reusable Code)

import math

def find_lcm(a, b):
    return abs(a * b) // math.gcd(a, b)

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

# Calling function
lcm = find_lcm(num1, num2)

# Printing the result
print("LCM of", num1, "and", num2, "is:", lcm)

Output

Enter first number: 8
Enter second number: 14
LCM of 8 and 14 is: 56
Share your love
Subhankar Rakshit
Subhankar Rakshit

Hey there! I’m Subhankar Rakshit, the brains behind PySeek. I’m a Post Graduate in Computer Science. PySeek is where I channel my love for Python programming and share it with the world through engaging and informative blogs.

Articles: 215