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

 Live Demo

#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;
}

Updated on: 25-Jun-2020

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements