LCM of Two Numbers in C++
LCM in C++ is (a × b) / GCD. LCM(12, 18) is 36. Save a and b before Euclid.
1#include <iostream>2using namespace std;34int main() {5 int a, b, gcd, lcm;67 cout << "Enter two numbers: ";8 cin >> a >> b;910 int originalA = a, originalB = b;1112 // Find GCD first13 while (b != 0) {14 int temp = b;15 b = a % b;16 a = temp;17 }18 gcd = a;1920 // LCM = (a * b) / GCD21 lcm = (originalA * originalB) / gcd;2223 cout << "LCM of " << originalA << " and " << originalB << " is: " << lcm << endl;2425 return 0;26}
Output
Enter two numbers: 12 18 LCM of 12 and 18 is: 36
What's going on
LCM is the smallest positive integer both numbers divide. LCM(12, 18) is 36. Don't list multiples — use LCM = (a × b) / GCD.
cin >> a >> b;
int originalA = a, originalB = b;
The GCD loop eats a and b.
Same Euclid as the GCD program:
while (b != 0) { int temp = b; b = a % b; a = temp; }
gcd = a;
12 and 18 → GCD 6.
lcm = (originalA * originalB) / gcd;
(12 × 18) / 6 = 36. Use the originals. After the loop a is 6 and b is 0. (a * b) / gcd is 0.
Overflow: originalA * originalB can wrap before you divide. Safer: (originalA / gcd) * originalB when gcd divides originalA (it does). This program uses the textbook form.
Coprime pair: GCD(7, 5) = 1, LCM = 35. Equal pair: LCM(12, 12) = 12.
Sample print: LCM of 12 and 18 is: 36.