LCM of Two Numbers Using Simple Method

Algorithm

  • Initialize two integers a and b with the two numbers for which we want to find the LCM.
  • Initialize a variable max with the maximum of a and b.
  • Run an infinite loop. Inside the loop, check if max is completely divisible by a and b, it means that max is the LCM of a and b.
  • Else, increment max by 1 and continue the loop to check the next number.

C++ Program To Find LCM of Two Numbers using Simple Method

C++




// C++ program to find the LCM of two
// numbers using the if statement and
// while loop
#include <iostream>
using namespace std;
 
// Driver code
int main()
{
    int a = 15, b = 20, max_num, flag = 1;
 
    // Use ternary operator to get the
    // large number
    max_num = (a > b) ? a : b;
 
    while (flag) {
        // if statement checks max_num is completely
        // divisible by n1 and n2.
        if (max_num % a == 0 && max_num % b == 0) {
            cout << "LCM of " << a << " and " << b << " is "
                 << max_num;
            break;
        }
 
        // update by 1 on each iteration
        ++max_num;
    }
    return 0;
}


Output

LCM of 15 and 20 is 60

Complexity Analysis

  • Time complexity: O(a*b)
  • Auxiliary space: O(1)

C++ Program To Find LCM of Two Numbers

LCM (Least Common Multiple) of two numbers is the smallest number that is divisible by both numbers. For example, the LCM of 15 and 20 is 60, and the LCM of 15 and 25 is 75. In this article, we will learn to write a C++ program to find the LCM of two numbers.

We can find the LCM of two numbers in C++ using two methods:

Similar Reads

1. LCM of Two Numbers Using Simple Method

Algorithm...

2. LCM of Two Numbers Using Built-In std::lcm() Function

...

3. LCM of Two Numbers Using GCD

C++ has an inbuilt function lcm() to find the lcm of the two numbers. It is defined in header file....

Contact Us