GCD of Two Numbers

Program to find Greatest Common Divisor using Euclidean algorithm

IntermediateTopic: Loop Programs
Back

C++ GCD 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, temp;
    
    cout << "Enter two numbers: ";
    cin >> a >> b;
    
    int originalA = a, originalB = b;
    
    // Euclidean algorithm
    while (b != 0) {
        temp = b;
        b = a % b;
        a = temp;
    }
    
    cout << "GCD of " << originalA << " and " << originalB << " is: " << a << endl;
    
    return 0;
}
Output
Enter two numbers: 48 18
GCD of 48 and 18 is: 6

Understanding GCD of Two Numbers

This program finds the Greatest Common Divisor (GCD) of two numbers using the Euclidean algorithm. GCD is the largest positive integer that divides both numbers without leaving a remainder. The Euclidean algorithm is one of the oldest and most efficient algorithms in mathematics, dating back to ancient Greece.

---

1. What is GCD (Greatest Common Divisor)?

GCD of two numbers is the largest number that divides both of them exactly (without remainder).

Examples:

GCD of 48 and 18:
Divisors of 48: 1, 2, 3, 4, 6, 8, 12, 16, 24, 48
Divisors of 18: 1, 2, 3, 6, 9, 18
Common divisors: 1, 2, 3, 6

-

GCD = 6

(largest common divisor)

GCD of 12 and 8:
Divisors of 12: 1, 2, 3, 4, 6, 12
Divisors of 8: 1, 2, 4, 8
Common divisors: 1, 2, 4

-

GCD = 4

GCD is used in:

Simplifying fractions (12/18 = 2/3, where GCD(12,18)=6)
Cryptography and number theory
Finding LCM (Least Common Multiple)
Many mathematical algorithms

---

2. Header File: #include <iostream>

#include <iostream>

Provides:

cout → for displaying output
cin → for reading input

---

3. Declaring Variables

int a, b, temp;

Variable `a` and `b`:

Store the two numbers entered by the user
These values will be modified during the algorithm
a will eventually hold the GCD

Variable `temp`:

Temporary variable used for swapping values
Needed because we modify a and b during the algorithm

Why save original values?

int originalA = a, originalB = b;

We save the original values because a and b will be modified
Needed for displaying the result: "GCD of 48 and 18 is: 6"

---

4. Understanding the Euclidean Algorithm

The Euclidean algorithm is based on a key mathematical property:

GCD(a, b) = GCD(b, a % b)

This means:

The GCD of two numbers equals the GCD of the smaller number and the remainder when dividing the larger by the smaller
We repeat this process until the remainder becomes 0
When remainder is 0, the other number is the GCD

Why this works:

If d divides both a and b, it also divides a % b
The GCD remains the same through each iteration
Eventually, one number becomes 0, and the other is the GCD

---

5. The Algorithm Step-by-Step

while (b != 0) {

temp = b;

b = a % b;

a = temp;

}

How it works:

Iteration 1 (a = 48, b = 18):

temp = btemp = 18
b = a % bb = 48 % 18 = 12 (remainder when 48 ÷ 18)
a = tempa = 18
Now: a = 18, b = 12
Check: b != 012 != 0

true

, continue

Iteration 2 (a = 18, b = 12):

temp = 12
b = 18 % 12 = 6
a = 12
Now: a = 12, b = 6
Check: 6 != 0

true

, continue

Iteration 3 (a = 12, b = 6):

temp = 6
b = 12 % 6 = 0 (12 is divisible by 6)
a = 6
Now: a = 6, b = 0
Check: 0 != 0

false

,

loop stops

Result:

a = 6 is the GCD ✅

---

6. Visual Representation

Finding GCD(48, 18):

Step 1: GCD(48, 18)

48 ÷ 18 = 2 remainder 12

→ GCD(48, 18) = GCD(18, 12)

Step 2: GCD(18, 12)

18 ÷ 12 = 1 remainder 6

→ GCD(18, 12) = GCD(12, 6)

Step 3: GCD(12, 6)

12 ÷ 6 = 2 remainder 0

→ GCD(12, 6) = GCD(6, 0)

When second number is 0, GCD is the first number

→ GCD = 6 ✅

---

7. Why Save Original Values?

We save originalA and originalB because:

a and b are modified during the algorithm
At the end, a contains the GCD, but we lost the original numbers
We need originals for the output message

Without saving:

Output would be: "GCD of 6 and 0 is: 6" ❌ (wrong!)

With saving:

Output: "GCD of 48 and 18 is: 6" ✅ (correct!)

---

8. Why This Algorithm is Efficient

Naive approach (checking all divisors):

Find all divisors of both numbers
Find common divisors
Return the largest

-

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

Euclidean algorithm:

Uses mathematical property to reduce problem size quickly
Each iteration reduces the numbers significantly

-

Time complexity: O(log(min(a, b)))

Much faster for large numbers!

Example:

GCD(1000000, 999999) with naive: ~1,000,000 operations
GCD(1000000, 999999) with Euclidean: ~20 operations

---

9. Edge Cases

Case 1: One number is 0

GCD(0, 5) = 5 (GCD is the non-zero number)
GCD(5, 0) = 5

Case 2: Both numbers are equal

GCD(12, 12) = 12
Algorithm: 12 % 12 = 0, so GCD = 12

Case 3: One divides the other

GCD(12, 4) = 4
Algorithm: 12 % 4 = 0, so GCD = 4

Case 4: Coprime numbers (GCD = 1)

GCD(7, 5) = 1
These numbers share no common factors except 1

---

10. Displaying the Result

`cout << "GCD of " << originalA << " and " << originalB << " is: " << a << endl;`

This prints:

Text: "GCD of "
Original first number: 48
Text: " and "
Original second number: 18
Text: " is: "
GCD value: 6
New line

Output:

GCD of 48 and 18 is: 6

---

Summary

Euclidean algorithm efficiently finds GCD using the property: GCD(a, b) = GCD(b, a % b)
The algorithm repeatedly applies modulo operation until remainder is 0
When remainder becomes 0, the other number is the GCD
Time complexity is O(log(min(a, b))), making it very efficient
This algorithm is fundamental in number theory and used in many applications

Understanding the Euclidean algorithm is crucial for:

Simplifying fractions
Finding LCM
Solving modular arithmetic problems
Cryptography algorithms
Many competitive programming problems

This is one of the most elegant and efficient algorithms in computer science, and mastering it opens doors to solving many mathematical programming problems.

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 GCD 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