(Translated by https://www.hiragana.jp/)
Program to find LCM of two numbers - GeeksforGeeks
Open In App

Program to find LCM of two numbers

Last Updated : 23 Jun, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given two positive integers and b. Find the Least Common Multiple (LCM) of a and b.
LCM of two numbers is the smallest number which can be divided by both numbers. 

Input : a = 10, b = 5
Output : 10
Explanation : 10 is the smallest number divisible by both 10 and 5

Input : a = 5, b = 11
Output : 55
Explanation : 55 is the smallest number divisible by both 5 and 11

[Naive Approach] Using Conditional Loop

This approach to calculating the Least Common Multiple (LCM) involves starting from the greater of the two numbers and checking if it's divisible by the smaller number. It iterates through multiples of the larger number, incrementing by the larger number itself in each step. The first multiple that is divisible by the smaller number is the LCM. This method is simple and intuitive, but it can be inefficient, especially for large numbers, as it checks multiple values until a match is found.

C++
Java Python C# JavaScript

Output
10

Time Complexity: O(min(a,b))
Auxiliary Space: O(1)

[Expected Approach] Using GCD LCM Formula

An efficient solution is based on the below formula for LCM of two numbers 'a' and 'b'. 

relation---------between---------hcf---------and---------lcm_________

a x b = LCM(a, b) * GCD (a, b)

LCM(a, b) = (a x b) / GCD(a, b)

We have discussed function to find GCD of two numbers. Using GCD, we can find LCM. 

C++
Java Python C# JavaScript

Output
10

Time Complexity: O(log(min(a,b))
Auxiliary Space: O(log(min(a,b))


Java Program to Find LCM of Two Numbers

Similar Reads