Print LCM of Two Integers in C++

Computations and programming when combined make a very deadly combination. As the ability to solve complex mathematical questions in itself is a great deal. But when one has to do the same thing by writing up a code, things get somewhat more complicated. Not to mention the language your coding in also determines whether it’s going to be easy to difficult. So today we’re going to write a program to print LCM of Two Integers in C++.

 

What’s The Approach? 

 

  • Let us consider a and b to be the two Integers to find LCM of.

 

  • Firstly we’ll find the gcd of these two numbers, i.e, using a condition where if a becomes zero we’ll return b else we’ll recursively return b % a, a

 

  • Next, we’ll return multiplication of a with gcd of two numbers, and again multiply it with b. The returned value will be our LCM.

 

Also Read:  Print Cube Root of A Number in Java

 

C++ Program To Print LCM of Two Integers

 

Input:

 

a = 15, b = 20

 

Output:

 

LCM of 15 and 20 is 60

 

// 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 program to test above function
int main()
{
    int a = 15, b = 20;
    cout <<"LCM of " << a << " and "
        << b << " is " << lcm(a, b);
    return 0;
}

 

Ethix

I'm a coding geek interested in cyberspace who loves to write and read

Leave a Reply