
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ Program to Find G.C.D Using Recursion
In this article, we'll show you how to write a C++ program to find the Greatest Common Divisor(GCD) of two numbers using Recursion. The GCD of two numbers is the largest number that divides both of them without leaving a remainder. It is also known as the Greatest Common Factor (GCF).
For example, the GCD of 36 and 60 is 12, because 12 is the largest number that divides both 36 and 60 without a remainder.
Using Recursion to Find the GCD
To find the GCD, we use recursion. In recursion, a function keeps calling itself with updated values until it reaches a condition where it stops.
Here's how it works:
- If the second number is 0, the first number is GCD.
- If not, the function calls itself again with the second number and the remainder of the first number when divided by the second number.
- This repeats until the second number becomes 0. At that point, the first number is the GCD.
C++ Program to Find the GCD Using Recursion
Below is the complete C++ program where we use recursion to find the GCD of two numbers.
#include <iostream> using namespace std; // Recursive function to find GCD using Euclidean algorithm int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } int main() { int first = 36, second = 60; // Call the gcd function and print the result cout << "GCD of " << first << " and " << second << " is: " << gcd(first, second) << endl; return 0; }
Below shows the output where the GCD of 36 and 60 is calculated using recursion.
GCD of 36 and 60 is: 12
Time Complexity: O(log min(a,b)) because the size of the numbers reduces with each recursive step.
Space Complexity: O(log min(a,b)) because of recursion stack.