LCM of Two Numbers
Program to find Least Common Multiple of two numbers
IntermediateTopic: Loop Programs
C++ LCM of Two Numbers Program
This program helps you to learn the fundamental structure and syntax of C++ programming.
#include <iostream>
using namespace std;
int main() {
int a, b, gcd, lcm;
cout << "Enter two numbers: ";
cin >> a >> b;
int originalA = a, originalB = b;
// Find GCD first
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
gcd = a;
// LCM = (a * b) / GCD
lcm = (originalA * originalB) / gcd;
cout << "LCM of " << originalA << " and " << originalB << " is: " << lcm << endl;
return 0;
}Output
Enter two numbers: 12 18 LCM of 12 and 18 is: 36
Understanding LCM of Two Numbers
LCM (Least Common Multiple) is calculated using the relationship: LCM(a, b) = (a × b) / GCD(a, b). We first find the GCD using the Euclidean algorithm, then use it to calculate the LCM. This is more efficient than checking multiples.
Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.