Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

GCD of Two Numbers in C++

Find the greatest common divisor of two numbers in C++ with the Euclidean algorithm. Traces 48 and 18 down to 6 and explains why a % b shrinks so quickly.

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

Sample Output

GCD of 48 and 18 is: 6

Printed with the saved originals.

In this one

  • How the Euclidean algorithm replaces (a, b) with (b, a % b)
  • Why the loop stops when b becomes 0
  • Why the originals are saved before the loop
  • How GCD leads to LCM

How it works

  1. 1

    Read a = 48, b = 18 and save copies.

  2. 2

    While b != 0: temp = b, b = a % b, a = temp.

  3. 3

    (48,18) → (18,12) → (12,6) → (6,0).

  4. 4

    b is 0, so a = 6 is the GCD.

Edge cases

One input is 0

Enter 0 and 9.

First pass: temp = 9, b = 0 % 9 = 0, a = 9. The GCD is 9, which is correct.

Both zero

Enter 0 0.

The loop never runs and the program prints 0. GCD(0,0) is not defined in math, so validate input.

What's going on

GCD is the largest integer that divides both numbers. GCD(48, 18) is 6. This C++ program uses Euclid: replace (a, b) with (b, a % b) until b is 0. Then a is the GCD.

cin >> a >> b;

int originalA = a, originalB = b;

The loop overwrites a and b. Save copies for the print.

while (b != 0) {

temp = b;

b = a % b;

a = temp;

}

Walk 48 and 18:

48 % 18 = 12 → (18, 12)
18 % 12 = 6 → (12, 6)
12 % 6 = 0 → (6, 0) stop

a is 6. Print uses originalA and originalB: GCD of 48 and 18 is: 6.

If one number is 0, GCD is the other (Euclid stops immediately). Both 0 is undefined; this loop would hang or return 0 depending how you start — don't.

Order doesn't matter. GCD(18, 48) takes one extra remainder and lands on 6 too.

LCM is next: (a × b) / GCD. You need this loop first.

Quiz

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

Question 1

What is GCD(20, 8) by Euclid?

Pick an answer to check it.

Question 2

Why use temp in the loop?

Pick an answer to check it.

Questions people ask

Why does Euclid work?

Any number that divides both a and b also divides a % b, so the common divisors never change while the numbers shrink.

Is there a library function?

C++17 has std::gcd in <numeric>.

Does the order of inputs matter?

No. If a < b, the first pass just swaps them.