In this C++ tutorial, you will learn how to write a program to find the LCM (Least Common Multiple) of given two numbers.

LCM of Two Numbers Program in C++

To find the LCM of two numbers in C++, take largest of the two numbers in lcm, and increment lcm till their product, wherein during each increment check if lcm does not leave any reminder when divided by the given two numbers.

Second method of find LCM is using LCM formula with HCF, where LCM = (product of given two numbers) / HCF.

Method 1 – Find LCM of two numbers

In the following program, we read two numbers to n1 and n2, and find their LCM.

We first assign the result lcm with the biggest number, then check if the value in lcm divides the two numbers without any remainder. If not, decrement the value in lcm and repeat the process.

C++ Program

#include <iostream>
using namespace std;

int main() {
    int n1, n2;
    cout << "Enter first number : ";
    cin >> n1;
    cout << "Enter second number : ";
    cin >> n2;
    
    int lcm;
    lcm = (n1 > n2) ? n1 : n2;

    do {
        if (lcm % n1 == 0 && lcm % n2 == 0) {
            break;
        }
        else {
            lcm++;
        }
    } while (lcm < (n1 * n2));
    
    cout << "LCM : " << lcm << endl;
}

Output

Enter first number : 12
Enter second number : 30
LCM : 60
Program ended with exit code: 0
Enter first number : 10
Enter second number : 15
LCM : 30
Program ended with exit code: 0
ADVERTISEMENT

Method 2 – Find LCM using formula

In the following program, we read two numbers to n1 and n2, and find their HCF. Using HCF we compute LCM using the formula.

C++ Program

#include <iostream>
using namespace std;

int main() {
    int n1, n2;
    cout << "Enter first number : ";
    cin >> n1;
    cout << "Enter second number : ";
    cin >> n2;
    
    int hcf = n1, temp = n2;
    while(hcf != temp) {
        if(hcf > temp)
            hcf = hcf - temp;
        else
            temp = temp - hcf;
    }
    
    int lcm = (n1 * n2) / hcf;
    
    cout << "LCM : " << lcm << endl;
}

Output

Enter first number : 12
Enter second number : 30
LCM : 60
Program ended with exit code: 0
Enter first number : 10
Enter second number : 15
LCM : 30
Program ended with exit code: 0

Conclusion

In this C++ Tutorial, we learned how to find LCM of two numbers in C++, with example programs.