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

GCD using Recursion in C++

Recursive GCD in C++ using Euclid's algorithm: why gcd(b, a % b) works, a dry run for 48 and 18, negatives, LCM from GCD, and the zero-input case.

IntermediateRecursion ProgramsExample 4 of 5
gcd-using-recursion.cpp
1#include <iostream>
2using namespace std;
3
4// Recursive function to calculate GCD using Euclidean algorithm
5int gcd(int a, int b) {
6 // Base case
7 if (b == 0) {
8 return a;
9 }
10
11 // Recursive case
12 return gcd(b, a % b);
13}
14
15int main() {
16 int num1, num2;
17
18 cout << "Enter two numbers: ";
19 cin >> num1 >> num2;
20
21 // Handle negative numbers
22 num1 = abs(num1);
23 num2 = abs(num2);
24
25 int result = gcd(num1, num2);
26
27 cout << "GCD of " << num1 << " and " << num2 << " = " << result << endl;
28
29 // Calculate LCM using GCD
30 int lcm = (num1 * num2) / result;
31 cout << "LCM of " << num1 << " and " << num2 << " = " << lcm << endl;
32
33 // Test with multiple pairs
34 cout << "\nGCD of various pairs:" << endl;
35 int pairs[][2] = {{48, 18}, {100, 25}, {17, 13}, {56, 42}};
36
37 for (int i = 0; i < 4; i++) {
38 int a = pairs[i][0];
39 int b = pairs[i][1];
40 cout << "GCD(" << a << ", " << b << ") = " << gcd(a, b) << endl;
41 }
42
43 return 0;
44}

Sample Output

LCM of 48 and 18 = 144

48 × 18 ÷ 6.

GCD(17, 13) = 1

Coprime numbers.

In this one

  • How Euclid's algorithm shrinks the problem
  • Why the base case is b == 0
  • How to get the LCM from the GCD
  • How to avoid overflow in the LCM

How it works

  1. 1

    Read two numbers and take abs.

  2. 2

    gcd(a, b) returns a when b is 0.

  3. 3

    Otherwise it returns gcd(b, a % b).

  4. 4

    LCM = num1 × num2 ÷ GCD.

  5. 5

    Print GCDs for four test pairs.

Dry run: GCD using Recursion

gcd(48, 18)

  1. 1.→ gcd(18, 48 % 18 = 12)
  2. 2.→ gcd(12, 18 % 12 = 6)
  3. 3.→ gcd(6, 12 % 6 = 0)
  4. 4.→ 6
gcd(48, 18)
→ gcd(18, 48 % 18 = 12)
→ gcd(12, 18 % 12 = 6)
→ gcd(6, 12 % 6 = 0)
→ 6

Edge cases

Both zero

Enter 0 0.

gcd returns 0, and the LCM line divides by 0, which is undefined behavior and usually crashes. Check for zero before computing the LCM.

One zero

Enter 0 5.

gcd(0, 5) → gcd(5, 0) = 5, and the LCM is 0.

Large inputs

Enter 100000 99999.

num1 * num2 overflows int before the division. Compute num1 / result * num2 instead.

What's going on

The greatest common divisor (GCD) of two numbers is the largest number that divides both. This program finds it with Euclid's algorithm, written as a two-line recursion.

The rule is gcd(a, b) = gcd(b, a % b), and gcd(a, 0) = a. It works because any number that divides both a and b also divides a % b, so the pair shrinks while the GCD stays the same.

For 48 and 18: gcd(48, 18) → gcd(18, 12) → gcd(12, 6) → gcd(6, 0) → 6. Each step the remainder drops quickly, so it takes only a handful of calls even for large numbers. The number of steps grows with the number of digits, not the size of the values.

If a < b, the first step swaps them automatically: gcd(18, 48) → gcd(48, 18 % 48) = gcd(48, 18).

main first takes abs() of both inputs, so negative numbers work. (abs comes from <cstdlib>; it compiles here because <iostream> happens to pull it in on common compilers, but including <cstdlib> is the portable choice.)

The LCM line uses the identity lcm(a, b) = a × b ÷ gcd(a, b), giving 144 for 48 and 18. Multiplying first can overflow int for large inputs; a / gcd * b gives the same result with a smaller intermediate value.

The test table checks four pairs, including 17 and 13, which are coprime, so their GCD is 1.

The headers come first. <iostream> is there because it provides cout and cin for input/output operations. Leave one out and the compiler stops at the first name it does not recognize.

Understanding GCD

GCD Definition:

Largest positive integer that divides both numbers
No remainder when dividing both
Common factor of both numbers
Fundamental in number theory

Example:

GCD(48, 18) = 6
48 ÷ 6 = 8, 18 ÷ 6 = 3
6 is largest common divisor

Euclidean Algorithm

Mathematical Principle:

gcd(a, b) = gcd(b, a % b)
Repeatedly apply until b = 0
When b = 0, gcd = a
Efficient and elegant

What happens here:

Reduces problem size each step
Uses modulo operation
Converges quickly
Logarithmic time complexity

Base Case

Stopping Condition:

if (b == 0) {

return a;

}

What happens here:

When b becomes 0, a is the GCD
Stops recursion
Returns result
Essential termination

Recursive Case

Function Calls Itself:

return gcd(b, a % b);

What happens here:

Swaps parameters: (b, a % b)
Reduces problem size
Modulo gives remainder
Continues until base case

Recursion Flow

Example: gcd(48, 18):

1.gcd(48, 18) → gcd(18, 48 % 18) = gcd(18, 12)
2.gcd(18, 12) → gcd(12, 18 % 12) = gcd(12, 6)
3.gcd(12, 6) → gcd(6, 12 % 6) = gcd(6, 0)
4.Base case: b = 0, return 6
5.Result: GCD = 6

Calculating LCM

Using GCD:

lcm(a, b) = (a * b) / gcd(a, b)

What happens here:

Relationship between GCD and LCM
Product divided by GCD
Efficient calculation
Uses computed GCD

Time Complexity

Efficiency:

O(log(min(a, b)))
Very efficient algorithm
Logarithmic time
Fast even for large numbers

Why Efficient:

Problem size reduces quickly
Modulo operation efficient
Few recursive calls
Optimal algorithm

When to Use Recursive GCD

Good fits:

Finding common divisors
Simplifying fractions
Calculating LCM
Number theory problems
Cryptography applications

Example Scenarios:

Fraction simplification
Modular arithmetic
Cryptography
Algorithm design
Mathematical computations

Important Considerations

Efficiency:

Very efficient algorithm
Logarithmic time complexity
Optimal for GCD calculation
Industry standard

Mathematical Foundation:

Based on Euclidean algorithm
Proven mathematical principle
Efficient and correct
Widely used

Recursive Elegance:

Natural recursive structure
Simple implementation
Easy to understand
Demonstrates recursion power

return 0;

return 0; closes main and tells the operating system the program finished without an error.

Quiz

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

Question 1

What is gcd(56, 42)?

Pick an answer to check it.

Question 2

Why does gcd(18, 48) still work?

Pick an answer to check it.

Questions people ask

Is there a built-in GCD?

Yes, std::gcd and std::lcm in <numeric> since C++17.

How many steps does Euclid take?

At most about five times the number of digits of the smaller number.

Why not just try every number down from the smaller one?

That is O(min(a, b)); Euclid is O(log min(a, b)).