Program to find LCM

0 Suresh Chand March 28, 2021

In this example, we will learn how to find LCM of two numbers using C++ programming language.

For this, You must have knowledge in following topics

We have to find the smallest possible number that divisible by both numbers. For example, We have 10, 20 then LCM will be 20.

Let’s look an example to make clear concepts

#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, b;

    cout << "Enter Two Integer : " << endl;
    cin >> a >> b;

    cout << "LCM of " << a << " and " << b << " is " << (a*b) / gcd(a, b);
    return 0;

}

The output of above program is

Enter Two Integer : 
10
35
LCM of 10 and 35 is 70

This the above example, First we will find the get two integer from users and stored in a and b.

Here we have used recursive function to find example.

We can also find the LCM without using any functions.

Example: LCM Without Function

#include <iostream>
using namespace std;

int main()
{
    int a, b, max;

    cout << "Enter two Integers: " << endl;
    cin >> a >> b;
    
    // maximum value between a and b is stored in max
    max = (a > b) ? a : b;

    do
    {
        if (max % a == 0 && max % b == 0)
        {
            cout << "LCM of " << a << " and " << b << " is " << max;
            break;
        }
        else
            ++max;
    } while (true);
    
    return 0;
}

The output remain same as above code.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Join Our Newsletter Now

Get the latest tutorials, examples and projects updates.

Ads Block Detector Powered by codehelppro.com

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.

Disable Ad Block

Want Same System