C++ Program To Find LCM of Two Numbers

Last Updated : 18 Aug, 2026

The Least Common Multiple (LCM) of two numbers is the smallest positive number that is divisible by both numbers. For example, the LCM of 15 and 20 is 60.

  • LCM is useful in problems involving common multiples and repeating intervals.
  • It can be calculated using a simple search, the std::lcm() function, or the GCD-based formula.

Illustration

Input: a = 15, b = 20
Output: LCM = 60

Explanation: 60 is the smallest positive number that is divisible by both 15 and 20.

LCM in C++

Methods to Find LCM of Two Numbers

The LCM can be calculated using the following approaches:

Method 1: Using Simple Iteration

Start from the larger of the two numbers and check each successive number until finding one that is divisible by both numbers.

Approach:

  • Initialize two numbers a and b.
  • Start checking from max(a, b).
  • If the current number is divisible by both a and b, it is the LCM.
  • Otherwise, increment the number and continue checking.
C++
#include <iostream>
#include <algorithm>
using namespace std;

int main()
{
    int a = 15, b = 20;

    int lcm = max(a, b);

    while (lcm % a != 0 || lcm % b != 0)
        lcm++;

    cout << "LCM of " << a << " and " << b << " is "
         << lcm;

    return 0;
} 

Output
LCM of 15 and 20 is 60

Method 2: Using Built-in std::lcm()

C++17 provides the std::lcm() function in the <numeric> header to directly calculate the LCM of two integers.

Syntax

std::lcm(a, b);

C++
#include <iostream>
#include <numeric>
using namespace std;

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

Method 3: Using GCD

The LCM of two numbers can be efficiently calculated using their GCD. The relationship is:

LCM(a, b) × GCD(a, b) = |a × b|

Therefore:

LCM(a, b) = |(a / GCD(a, b)) × b|

Dividing before multiplying helps reduce the chance of intermediate overflow.

C++
#include <iostream>
#include <numeric>
using namespace std;

int main()
{
    long long a = 15, b = 20;

    long long g = gcd(a, b);
    long long lcm = (a / g) * b;

    cout << "LCM of " << a << " and " << b << " is "
         << lcm;

    return 0;
} 
Try It Yourself
redirect icon

Output
LCM of 15 and 20 is 60
Comment