LCM of Two Numbers

Program to find Least Common Multiple of two numbers

IntermediateTopic: Loop Programs
Back

C++ LCM of Two Numbers Program

This program helps you to learn the fundamental structure and syntax of C++ programming.

Try This Code
#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

This program finds the Least Common Multiple (LCM) of two numbers. LCM is the smallest positive integer that is divisible by both numbers. The program uses an efficient method: first finding the GCD (Greatest Common Divisor), then calculating LCM using the mathematical relationship between GCD and LCM.

---

1. What is LCM (Least Common Multiple)?

LCM of two numbers is the smallest number that is a multiple of both numbers.

Examples:

LCM of 12 and 18:
Multiples of 12: 12, 24, 36, 48, 60, 72, ...
Multiples of 18: 18, 36, 54, 72, 90, ...
Common multiples: 36, 72, 108, ...

-

LCM = 36

(smallest common multiple)

LCM of 4 and 6:
Multiples of 4: 4, 8, 12, 16, 20, ...
Multiples of 6: 6, 12, 18, 24, ...
Common multiples: 12, 24, ...

-

LCM = 12

LCM is used in:

Adding/subtracting fractions with different denominators
Finding when events repeat (e.g., two clocks chiming together)
Scheduling problems
Many mathematical applications

---

2. The Relationship Between GCD and LCM

There's a beautiful mathematical relationship:

LCM(a, b) × GCD(a, b) = a × b

Rearranging:

LCM(a, b) = (a × b) / GCD(a, b)

Why this works:

GCD contains the common factors of both numbers
When we multiply a and b, we get all factors (common and unique)
Dividing by GCD removes the common factors, leaving only what's needed for LCM

Example with 12 and 18:

GCD(12, 18) = 6
LCM(12, 18) = (12 × 18) / 6 = 216 / 6 =

36

---

3. Header File: #include <iostream>

#include <iostream>

Provides:

cout → for displaying output
cin → for reading input

---

4. Declaring Variables

int a, b, gcd, lcm;

Variable `a` and `b`:

Store the two numbers entered by the user
Will be modified during GCD calculation

Variable `gcd`:

Stores the Greatest Common Divisor
Calculated first using Euclidean algorithm

Variable `lcm`:

Stores the Least Common Multiple
Calculated using the formula: LCM = (a × b) / GCD

Saving original values:

int originalA = a, originalB = b;

We save originals because a and b will be modified
Needed for both GCD calculation and final output

---

5. Taking Input From User

`cout << "Enter two numbers: ";`

cin >> a >> b;

Prompts user to enter two numbers
Reads and stores them in a and b

Example:

User enters:

12 18

a = 12, b = 18

---

6. Finding GCD Using Euclidean Algorithm

while (b != 0) {

int temp = b;

b = a % b;

a = temp;

}

gcd = a;

This is the Euclidean algorithm we learned in the GCD program.

// Find GCD first

Step-by-step (for a = 12, b = 18):

Iteration 1:

temp = 18
b = 12 % 18 = 12
a = 18
Now: a = 18, b = 12

Iteration 2:

temp = 12
b = 18 % 12 = 6
a = 12
Now: a = 12, b = 6

Iteration 3:

temp = 6
b = 12 % 6 = 0
a = 6
Now: a = 6, b = 0
Loop stops

Result:

gcd = 6

---

7. Calculating LCM Using the Formula

lcm = (originalA * originalB) / gcd;

Why use originalA and originalB?

a and b were modified during GCD calculation
a now contains the GCD (6)
b is now 0
We need the original values (12 and 18) for the formula

Calculation:

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

---

8. Why This Method is Efficient

Naive approach (checking multiples):

Start from the larger number
Check each multiple to see if it's divisible by both
Stop at the first common multiple

-

Time complexity: O(max(a, b))

Our approach (using GCD):

Find GCD: O(log(min(a, b)))
Calculate LCM: O(1) (just multiplication and division)

-

Total: O(log(min(a, b)))

Much faster!

Example:

LCM(1000000, 999999) with naive: ~1,000,000 checks
LCM(1000000, 999999) with our method: ~20 operations for GCD + 1 for LCM

---

9. Complete Example Walkthrough

Input:

a = 12, b = 18

Step 1: Save originals

originalA = 12, originalB = 18

Step 2: Find GCD

Apply Euclidean algorithm
Result: gcd = 6

Step 3: Calculate LCM

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

Step 4: Display result

Output: "LCM of 12 and 18 is: 36"

---

10. Verification

Let's verify the result:

-

Multiples of 12:

12, 24, 36, 48, 60, ...

-

Multiples of 18:

18, 36, 54, 72, ...

-

Common multiples:

36, 72, 108, ...

-

Smallest common multiple:

36 ✅

Also verify the relationship:

GCD(12, 18) = 6
LCM(12, 18) = 36

-

6 × 36 = 216

-

12 × 18 = 216

Relationship holds: GCD × LCM = a × b

---

11. Edge Cases

Case 1: One number is a multiple of the other

LCM(12, 4) = 12
GCD(12, 4) = 4
LCM = (12 × 4) / 4 = 48 / 4 = 12 ✅

Case 2: Both numbers are equal

LCM(12, 12) = 12
GCD(12, 12) = 12
LCM = (12 × 12) / 12 = 144 / 12 = 12 ✅

Case 3: Coprime numbers (GCD = 1)

LCM(7, 5) = 35
GCD(7, 5) = 1
LCM = (7 × 5) / 1 = 35 / 1 = 35 ✅

---

12. Displaying the Result

`cout << "LCM of " << originalA << " and " << originalB << " is: " << lcm << endl;`

This prints:

Text: "LCM of "
Original first number: 12
Text: " and "
Original second number: 18
Text: " is: "
LCM value: 36
New line

Output:

LCM of 12 and 18 is: 36

---

Summary

LCM is the smallest number divisible by both given numbers
Efficient method: LCM(a, b) = (a × b) / GCD(a, b)
First find GCD using Euclidean algorithm
Then calculate LCM using the formula
This method is much faster than checking multiples
Understanding GCD and LCM relationship is crucial for many mathematical problems

This program demonstrates:

How to combine algorithms (GCD + LCM calculation)
Using mathematical relationships for efficiency
The importance of saving original values
Practical application of number theory

Mastering LCM calculation helps in:

Fraction arithmetic
Solving scheduling problems
Finding common denominators
Many real-world applications

The relationship between GCD and LCM is one of the most elegant in mathematics, and this program shows how to use it efficiently in programming.

Let us now understand every line and the components of the above program.

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.

Practical Learning Notes for LCM of Two Numbers

This C++ program is part of the "Loop Programs" topic and is designed to help you build real problem-solving confidence, not just memorize syntax. Start by understanding the goal of the program in plain language, then trace the logic line by line with a custom input of your own. Once you can predict the output before running the code, your understanding becomes much stronger.

A reliable practice pattern is to run the original version first, then modify only one condition or variable at a time. Observe how that single change affects control flow and output. This deliberate style helps you understand loops, conditions, and data movement much faster than copying full solutions repeatedly.

For interview preparation, explain this solution in three layers: the high-level approach, the step-by-step execution, and the time-space tradeoff. If you can teach these three layers clearly, you are ready to solve close variations of this problem under time pressure.

Table of Contents