Open In App

C++ Program To Find LCM of Two Numbers

LCM (Least Common Multiple) of two numbers is the smallest number that is divisible by both numbers. For example, the LCM of 15 and 20 is 60, and the LCM of 15 and 25 is 75. In this article, we will learn to write a C++ program to find the LCM of two numbers.



We can find the LCM of two numbers in C++ using two methods:

1. LCM of Two Numbers Using Simple Method

Algorithm

C++ Program To Find LCM of Two Numbers using Simple Method




// C++ program to find the LCM of two
// numbers using the if statement and
// while loop
#include <iostream>
using namespace std;
 
// Driver code
int main()
{
    int a = 15, b = 20, max_num, flag = 1;
 
    // Use ternary operator to get the
    // large number
    max_num = (a > b) ? a : b;
 
    while (flag) {
        // if statement checks max_num is completely
        // divisible by n1 and n2.
        if (max_num % a == 0 && max_num % b == 0) {
            cout << "LCM of " << a << " and " << b << " is "
                 << max_num;
            break;
        }
 
        // update by 1 on each iteration
        ++max_num;
    }
    return 0;
}

Output

LCM of 15 and 20 is 60

Complexity Analysis

2. LCM of Two Numbers Using Built-In std::lcm() Function

C++ has an inbuilt function lcm() to find the lcm of the two numbers. It is defined in <numeric> header file.

Syntax

lcm(num1, num2);

where num1 and num2 are the two numbers.

Note: This function is only available since C++17.

C++ Program to Find LCM Using std::lcm() Function




// CPP program to illustrate how to find lcm of two numbers
// using std::lcm function
#include <iostream>
#include <numeric>
 
using namespace std;
 
int main()
{
    cout << "LCM(10,20) = " << lcm(10, 20) << endl;
    return 0;
}

Output

LCM(10,20) = 20

Complexity Analysis

3. LCM of Two Numbers Using GCD

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

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

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

C++ Program to Find LCM Using GCD




// C++ program to find LCM
// of two numbers
#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 code
int main()
{
    int a = 15, b = 20;
    cout << "LCM of " << a << " and " << b << " is "
         << lcm(a, b);
 
    return 0;
}

Complexity Analysis

Refer to the complete article Program to find LCM of two numbers for more details.

Related Articles


Article Tags :