Home »
C++ programs
C++ program to find LCM of two numbers
Here, we are going to learn how to find LCM of two numbers using simple way and LCM using GCD?
Submitted by Vivek Kothari, on November 17, 2018
LCM (least common multiple) of two given numbers m and n is determined by finding the smallest number that is divisible by both the numbers. A simple approach to this problem is to store the maximum of a and b in variable max and check if max is completely divisible by both the numbers, if yes then max is the lcm otherwise increment max by 1.
C++ program to find LCM using simple approach
#include <iostream>
using namespace std;
int main()
{
int m,n,max;
m=12;
n=15;
if(m > n)
max= m;
else
max = n;
while(true)
{
if (max % m == 0 && max % n == 0)
{
cout << "LCM of "<<m<<" and "<<n<<" = "<< max;
break;
}
else
max++;
}
return 0;
}
Output
LCM of 12 and 15 = 60
C++ program to find LCM using GCD
We can also use the property of LCM and HCF, we know that the product of two numbers is equal to the product of LCM and HCF.
Therefore LCM of two numbers is given by:
LCM = (n1 * n2) / HCF
We know that, HCF (highest common factor) = GCD (greatest common divisor)
So, LCM = (n1 * n2) / GCD
#include <iostream>
using namespace std;
//function to return gcd of a and b
int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
int main()
{
int m,n;
m=12;
n=15;
cout<<"LCM of "<<m<<" and "<<n<<" = "<<(m*n)/gcd(m,n)<<endl;
m=7;
n=100;
cout<<"LCM of "<<m<<" and "<<n<<" = "<<(m*n)/gcd(m,n);
}
Output
LCM of 12 and 15 = 60
LCM of 7 and 100 = 700