lcm c++ – C++ Program to Find LCM of Two Numbers

lcm c++: In the previous article, we have discussed about C++ Program to Convert Decimal Number to Octal Number. Let us learn how to Find LCM of Two Numbers in C++ Program.

Methods to find lcm of two numbers in C++

In this article, we discuss how we can find the lcm of two numbers. The methods that we will discuss are given below.

First of all, let us understand what an LCM is. LCM or the Least Common Multiple of two numbers is defined as the smallest number which can be divisible by both the numbers. For example, the LCM of 15 and 25 is 75 because 75 is the smallest number which can be divisible by both the numbers. Now let’s discuss different methods to find LCM.

Method 1-Using GCD

Here we will take the help of GCD for finding the LCM of two numbers. As we know that LCM*HCF=Product of two numbers.

Therefore LCM=Product of two numbers/HCF. So we use this formula to find the LCM of two numbers. Given below is the link to the article describing how to find the GCD/HCF of two numbers.

https://btechgeeks.com/cpp-program-to-find-gcd/

Let’s write the code for better understanding.

#include <iostream>
using namespace std;

int gcd(int a,int b)
{
if (b == 0)
    return a;
return gcd(b, a % b);
}

int lcm(int a, int b)
{
    return (a / gcd(a, b)) * b;
}

int main()
{
    int a = 15, b = 25;
    cout <<"LCM of " << a << " and "
        << b << " is " << lcm(a, b);
    return 0;
}

Output

LCM of 15 and 25 is 75

Method 2-Without using GCD

We can also find the lcm of two numbers without using GCD. Here we can use intuition like this that the largest number of two numbers can be LCM of two numbers because if a number has to be divisible by both the number then it is possible in this case. For example, LCM of 15 and 30 is 30. So here 30 is the largest among the two numbers. So we can start a loop from the largest number and runs the loop till we get a number that is divisible by both the numbers. Let’s write the code for this.

#include <iostream>
using namespace std;


int main()
{
    int a = 15, b = 25,i,lcm;
    for(i=b;;i++)
    {
        if(i%a==0 && i%b==0)
        {
            lcm=i;
            break;
        }
    }
    cout <<"LCM of " << a << " and "
        << b << " is " << lcm;
    return 0;
}

Output

LCM of 15 and 25 is 75

So these are the methods to find the LCM of two numbers.