LCM of Two Numbers in C++

LCM in C++ is (a × b) / GCD. LCM(12, 18) is 36. Save a and b before Euclid.

IntermediateLoop ProgramsExample 6 of 14
lcm-of-two-numbers.cpp
1#include <iostream>
2using namespace std;
3
4int main() {
5 int a, b, gcd, lcm;
6
7 cout << "Enter two numbers: ";
8 cin >> a >> b;
9
10 int originalA = a, originalB = b;
11
12 // Find GCD first
13 while (b != 0) {
14 int temp = b;
15 b = a % b;
16 a = temp;
17 }
18 gcd = a;
19
20 // LCM = (a * b) / GCD
21 lcm = (originalA * originalB) / gcd;
22
23 cout << "LCM of " << originalA << " and " << originalB << " is: " << lcm << endl;
24
25 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.