C++ Program to calculate the LCM


January 18, 2023, Learn eTutorial
1314

What is LCM?

This C++ program is for finding the LCM, and LCM stands for Least Common Multiple. LCM can be defined as the lowest number which is the perfect multiple of both the numbers

Example: let us find the LCM of 4 and 5.

  • Multiples of 4 are: 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, ...
  • Multiples of 5 are: 5, 10, 15, 20, 25, 30, 35, 40, ...
  • Hence, the LCM of 4 and 5 is 20. which is the lowest number that is multiple of both 4 and 5
calculate the LCM

How to implement the listing method for calculating LCM in C++?

calculate the LCM

The user is asked to enter two numbers. Read the values to the variables num1 and num2. Find the maximum value between num1 and num2 and store the maximum value in the variable max.

Here we are using the ternary or conditional operator ( ?: ) in C++. 
variable = Expression1 ? Expression2: Expression3

Here, Expression1 is the condition to be evaluated. If the condition(Expression1) is True then Expression2 will be executed and the result will be returned. Otherwise, if the condition(Expression1) is false then Expression3 will be executed and the result will be returned.
So, the comparison can be performed like  max = ( num1 > num2 ) ? num1 : num2

If num1 is greater than num2. Then max = num1 else max = num2; Now the variable max contains the largest among the two numbers.

Divide max with both variables. If max is evenly divisible by both num1 and num2 then LCM = max; else increase the value max by 1. Repeat the process of the division until we get a number that is evenly divisible by both the integers num1 and num2. Print the result. This can be performed by using an if-else statement and do------ while loop.

 

Algorithm

Step 1:  Call the header file iostream.

Step 2: Use the namespace std.

Step 3: Open the integer type main function; int main().

Step 4: Declare integer variable num1, num2, max;

Step 5: Print a message to enter two numbers.

Step 6: Read the number into the variables num1 and num2.

Step 7: compare num1 and num2. Load the greater value to the variable max;

Step 8: check whether if max is evenly divisible by both num1 and num2. Then print LCM = max

Step 9: else increment max by 1 and go to step 8.

Step 10: Exit;

C++ Source Code

                                          #include <iostream>
using namespace std;

int main()
{
    int num1, num2, max;

    cout << "Enter two numbers: ";
    cin >> num1 >> num2;
    
    // maximum value between num1 and num2 is stored in max
    max = (num1 > num2) ? num1 : num2;

    do
    {
        if (max % num1 == 0 && max % num2 == 0)
        {
            cout << "LCM = " << max;
            break;
        }
        else
            ++max;
    } while (true);
    
    return 0;
}
                                      

OUTPUT

Enter two numbers: 4
6
LCM = 12