Algorithm
Input: Accept two integers (n1
and n2
) from the user.
Find Maximum: Determine the maximum of the two input numbers (n1
and n2
) and store it in the variable max
.
Find LCM (Least Common Multiple):
Start a do-while loop that continues indefinitely (while(true)
).
Check if max
is divisible by both n1
and n2
using the modulo operator (%
).
If the condition is true, print the value of max
as the Least Common Multiple (LCM) and break out of the loop.
If the condition is false, increment max
by 1 and continue the loop.
Output: Display the LCM of the two input numbers.
End: Return 0 to indicate successful completion of the program.
Code Examples
#1 Code Example with C++ Programming
Code -
C++ Programming
#include <iostream>
using namespace std;
int main()
{
int n1, n2, max;
cout << "Enter two numbers: ";
cin >> n1 >> n2;
// maximum value between n1 and n2 is stored in max
max = (n1 > n2) ? n1 : n2;
do
{
if (max % n1 == 0 && max % n2 == 0)
{
cout << "LCM = " << max;
break;
}
else
++max;
} while (true);
return 0;
}
Copy The Code &
Try With Live Editor
Output
18
LCM = 36
#2 Example - C++ Programing Find LCM using HCF . The LCM of two numbers is given by: LCM = (n1 * n2) / HCF
Code -
C++ Programming
#include <iostream>
using namespace std;
int main()
{
int n1, n2, hcf, temp, lcm;
cout << "Enter two numbers: ";
cin >> n1 >> n2;
hcf = n1;
temp = n2;
while(hcf != temp)
{
if(hcf > temp)
hcf -= temp;
else
temp -= hcf;
}
lcm = (n1 * n2) / hcf;
cout << "LCM = " << lcm;
return 0;
}
Copy The Code &
Try With Live Editor
Demonstration
C++ Programing Example to Find LCM-DevsEnv