- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- 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 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.

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

63 = 7 * 3 * 3 21 = 7 * 3

So, the GCD of 63 and 21 is 21.

The recursive Euclid’s algorithm computes the GCD by using a pair of positive integers a and b and returning b and a%b till b is zero.

A program to find the GCD of two numbers using recursive Euclid’s algorithm is given as follows −

## Example

#include <iostream> using namespace std; int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } int main() { int a , b; cout<<"Enter the values of a and b: "<<endl; cin>>a>>b; cout<<"GCD of "<< a <<" and "<< b <<" is "<< gcd(a, b); return 0; }

## Output

The output of the above program is as follows −

Enter the values of a and b: 105 30 GCD of 105 and 30 is 15

In the above program, gcd() is a recursive function. It has two parameters i.e. a and b. If b is equal to 0, then a is returned to the main() function. Otherwise the gcd() function recursively calls itself with the values b and a%b. This is demonstrated by the following code snippet −

int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); }

In the main() function, values of a and b are requested from the user. Then gcd() function is called and the value of GCD of a and b is displayed. This is seen below −

int main() { int a , b; cout<<"Enter the values of a and b: "<<endl; cin>>a>>b; cout<<"GCD of "<< a <<" and "<< b <<" is "<< gcd(a, b); return 0; }

- Related Questions & Answers
- C program to find GCD of numbers using recursive function
- C program to find GCD of numbers using non-recursive function
- Java Program to Find GCD of two Numbers
- Find GCD of two numbers
- Program to find GCD or HCF of two numbers in C++
- C program to implement Euclid’ s algorithm
- Program to find GCD or HCF of two numbers using Middle School Procedure in C++
- Java program to find the GCD or HCF of two numbers
- Program to find GCD of floating point numbers in C++
- Find out the GCD of two numbers using while loop in C language
- C++ Program to Find the GCD and LCM of n Numbers
- C++ Program for GCD of more than two (or array) numbers?
- Program to compute gcd of two numbers recursively in Python
- Find HCF of two numbers without using recursion or Euclidean algorithm in C++
- C++ Program to Find GCD