C++ Program to Find LCM

C++ProgrammingServer Side Programming

The Least Common Multiple (LCM) of two numbers is the smallest number that is a multiple of both.

For example: Let’s say we have the following two numbers: 15 and 9.

15 = 5 * 3
9 = 3 * 3

So, the LCM of 15 and 9 is 45.

A program to find the LCM of two numbers is given as follows −

Example

 Live Demo

#include <iostream>
using namespace std;
int main() {
   int a=7, b=5, lcm;
   if(a>b)
   lcm = a;
   else
   lcm = b;
   while(1) {
      if( lcm%a==0 && lcm%b==0 ) {
         cout<<"The LCM of "<<a<<" and "<<b<<" is "<<lcm;
         break;
      }
      lcm++;
   }
   return 0;
}

Output

The LCM of 7 and 5 is 35

In the above program, the variable lcm is set as the larger of the two numbers. This is demonstrated using the following code snippet.

if(a>b)
lcm = a;
else
lcm = b;

After this, a while loop runs. In this loop, if LCM is divisible by a as well as b, it is the LCM of the two numbers and is displayed. If not, LCM is incremented until this condition is fulfilled.

The code snippet that explains this is as follows −

while(1) {
   if( lcm%a==0 && lcm%b==0 ) {
      cout<<"The LCM of "<<a<<" and "<<b<<" is "<<lcm;
      break;
   }
   lcm++;
}

Another method of finding the LCM of two numbers is to use the LCM and GCD formula. This formula specifies that the product of two numbers is equal to the product of their LCM and GCD.

a * b = GCD * LCM

A program to find the LCM of two numbers using the formula is given as follows −

Example

 Live Demo

#include<iostream>
using namespace std;
int gcd(int a, int b) {
   if (b == 0)
   return a;
   return gcd(b, a % b);
}
int main() {
   int a = 7, b = 5;
   cout<<"LCM of "<< a <<" and "<< b <<" is "<< (a*b)/gcd(a, b);
   return 0;
}

Output

LCM of 7 and 5 is 35

In the above program, the LCM is found using the formula. First, the GCD of a and b is obtained using gcd(). Itis a recursive function. It has two parameters i.e. a and b. If b is greater than 0, then a is returned to the main() function. Otherwise the gcd() function recursively calls itself with the values b and a%b.

This is demonstrated using the following code snippet.

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

After the GCD is obtained, the LCM is calculated using the formula. Then it is displayed. This is shown in the following code snippet.

cout<<"LCM of "<< a <<" and "<< b <<" is "<< (a*b)/gcd(a, b);
raja
Published on 27-Sep-2018 13:32:24
Advertisements