Calculating Lowest Common Multiple (LCM) in C++

Exercise:

Write a C++ program to find LCM.

Method 1: Finding LCM directly:

Click Here to View the Solution:
#include <iostream>
using namespace std;
int main()
{
    int num1, num2, val;
    cout << "Insert any two positive numbers:\n ";
    cin >> num1 >> num2;
    // least common multiple between num1 and num2 is stored in val
    val = (num1 > num2) ? num1 : num2;
    do
    {
        if (val % num1 == 0 && val % num2 == 0)
        {
            cout << "the LCM is: " << val;
            break;
        }
        else
        ++val;
    }
    while (true);
    return 0;
}

Click Here to View the Output:
Insert any two positive numbers:
 12
 32
 the LCM is: 96
Click Here to View the Explanation:
  • Smallest number that divides num1 and num2 is known as the LCM of the numbers. In short, LCM is the smallest possible common multiple of two provided numbers.
  • Two positive numbers are requested from the user and saved as a new variable: val.
  • Then it enters the loop, checking if value can be divided by num1 and num2. When the condition is satisfied/marked true, the list of common multiples is displayed on the screen on and loop is exited.
  • Otherwise, the number is decremented by 1 and run through the loop again.

Method 2: Finding LCM with the help of HCF:

Click Here to View the Solution:
#include <iostream>
using namespace std;
int main()
{
    int num1, num2, HCF, val, TemporaryVariable;
    cout << "Insert any two positive numbers:\n";
    cin >> num1 >> num2;
    HCF = num1;
    TemporaryVariable = num2;
    while(HCF != TemporaryVariable)
    {
        if(HCF > TemporaryVariable)
        HCF = HCF - TemporaryVariable;
        else
        TemporaryVariable = TemporaryVariable - HCF;
    }
    val = (num1 * num2) / HCF;
    cout << "the LCM is: " << val;
    return 0;
}
Click Here to View the Output:
Insert any two positive numbers:
 8
 12
 the LCM is: 24
Click Here to View the Explanation:
  • This code uses a temporary variable TemporaryVariable and saves the numbers entered by the user num1 and num2 as newer variables.
  • The values of num2 and num1 are saved in other variables TemporaryVariable and HCF.
  • While loops are added and entered every time TemporaryVariable isn’t equal to HCF. TemporaryVariable is subtracted from HCF, assigning new value of HCF.
  • Otherwise, HCF is subtracted from TemporaryVariable to assign a new value of TemporaryVariable.
  • Formula: (num1 * num2) / HCF is used to calculate the LCM. Output is displayed on the screen.

%d bloggers like this: