CodeRush Sale · 60% off all certificate courses until 15 Dec

LCM of Two Numbers in C++

Find the least common multiple of two numbers in C++ by computing the GCD first and using a × b / GCD. Covers coprime pairs and the overflow risk in a × b.

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}

Sample Output

LCM of 12 and 18 is: 36

12 × 18 / 6.

In this one

  • The relation LCM × GCD = a × b
  • How to reuse the Euclidean loop
  • Why the original values must be used in the formula
  • How to avoid overflow by dividing first

How it works

  1. 1

    Read 12 and 18 and save them.

  2. 2

    Run Euclid to get GCD 6.

  3. 3

    lcm = (12 × 18) / 6 = 36.

  4. 4

    Print the result.

Edge cases

Large inputs

Enter 100000 and 99999.

100000 × 99999 overflows a 32-bit int before the division. Writing (originalA / gcd) * originalB keeps numbers smaller.

Zero input

Enter 0 and 5.

GCD is 5 and LCM becomes 0. Many definitions say LCM with 0 is 0, but dividing by a GCD of 0 (both zero) would crash.

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.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

LCM(4, 6)?

Pick an answer to check it.

Question 2

For coprime a and b, LCM equals:

Pick an answer to check it.

Questions people ask

Why not use a and b after the loop?

The loop changed them: a is the GCD and b is 0, so a * b is 0.

Is there a built-in?

C++17 provides std::lcm in <numeric>.

What is LCM used for?

Finding when repeating events line up, or a common denominator for fractions.