C++ Program to Find GCD of Two Numbers Using Recursive Euclid Algorithm



The Greatest Common Divisor (GCD) of two numbers is the largest number that divides both of them. In this article we'll show you how to write a C++ program to find the GCD of two numbers using the recursive Euclid's algorithm.

For example: Let's say we have two numbers that are 63 and 21.

Input: 63 and 21
=> 63 = 7 * 3 * 3
=> 21 = 7 * 3
So, the GCD of 63 and 21 is 21.

Output: 21

Finding GCD Using Recursive Euclid Algorithm

The recursive Euclid algorithm helps us find the GCD by taking a pair of positive integers a and b, and repeatedly calling the function with b and a % b until b becomes zero. At that point, a is the GCD. Here's what we do:

  • First, we take two numbers.
  • Next, we check if the second number is zero. If it is, we know the first number is the GCD, so we return it.
  • If the second number isn't zero, we call the same process again but with the second number and the remainder when the first number is divided by the second.
  • We keep doing this until the second number becomes zero, and at that point, the first number is the GCD.

C++ Program to Find GCD Using Recursive Euclid Algorithm

Here's a C++ program to find the GCD of two numbers using recursive Euclid's algorithm.

#include <iostream>
using namespace std;

// This function finds the GCD of two numbers
int gcd(int a, int b) {
    if (b == 0)
        return a;
    return gcd(b, a % b);
}

int main() {
    int a = 36, b = 60; 
    // Call the GCD function and print the result
    cout << "GCD of " << a << " and " << b << " is " << gcd(a, b);
    return 0;
}

When you run the above program, you will see the output below showing the GCD of two numbers. You can try it with other numbers too.

GCD of 36 and 60 is 12

Time Complexity: O(log(min(a, b))) because each step reduces the smaller number.

Space Complexity: O(log(min(a, b))) because of the recursion calls stored in memory.

Updated on: 2025-08-18T18:44:02+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements