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
andnum2
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 bynum1
andnum2
. 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 usernum1
andnum2
as newer variables. - The values of
num2
andnum1
are saved in other variablesTemporaryVariable
andHCF
. While
loops are added and entered every timeTemporaryVariable
isn’t equal toHCF
.TemporaryVariable
is subtracted fromHCF
, assigning new value ofHCF
.- Otherwise,
HCF
is subtracted fromTemporaryVariable
to assign a new value ofTemporaryVariable
. - Formula:
(num1 * num2) / HCF
is used to calculate theLCM
. Output is displayed on the screen.