The Least Common Multiple () of two numbers is the smallest positive number that is divisible by both numbers without leaving a remainder.
- LCM is always a multiple of both given numbers.
- It can be calculated using a simple iteration or the GCD-based formula.
Example:
Input: x = 15, y = 25
Output: LCM of 15 and 25 is 75
Explanation: 75 is the smallest number that is divisible by both 15 and 25.

Approaches to Find LCM
There are two common approaches to find the LCM of two numbers in C:
1. LCM Using a Loop
Start from the larger of the two numbers and check each successive number until a number divisible by both given numbers is found.
- Find the larger of the two numbers and store it in max.
- Check whether max is divisible by both numbers.
- If it is, max is the LCM.
- Otherwise, increment max by 1 and repeat the process.
#include <stdio.h>
// Driver code
int main()
{
int x = 15, y = 25, max;
max = (x > y) ? x : y;
// While loop to check if max variable
// is divisible by x and y
while (1) {
if (max % x == 0 && max % y == 0) {
printf("The LCM of %d and %d is %d.", x, y,
max);
break;
}
++max;
}
return 0;
}
Output
The LCM of 15 and 25 is 75.
Explanation
- max is initialized with the larger of the two numbers.
- The while loop checks whether max is divisible by both numbers.
- If the condition is true, max is the LCM and the loop terminates.
- Otherwise, max is incremented and the next number is checked.
2. LCM Using GCD
The LCM can be calculated efficiently using the GCD of the two numbers. The relationship between LCM and GCD is:
LCM(a,b) = \frac{a \times b}{GCD(a,b)}
To avoid unnecessary overflow in the multiplication, we calculate it as:
LCM(a,b) = \frac{a}{GCD(a,b)} \times b
#include <iostream>
using namespace std;
// Recursive function to return gcd of a and b
long long gcd(long long int a, long long int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
// Function to return LCM of two numbers
long long lcm(int a, int b) { return (a / gcd(a, b)) * b; }
// Driver program to test above function
int main()
{
int a = 15, b = 20;
cout << "LCM of " << a << " and " << b << " is "
<< lcm(a, b);
return 0;
}
Output
LCM of 15 and 20 is 60
Explanation
- gcd() recursively calculates the GCD using the Euclidean algorithm.
- lcm() uses the GCD to calculate the LCM using the formula LCM(a, b) = (a / GCD(a, b)) × b.
- main() calls lcm() and prints the result.