Find GCD of two numbers

In mathematics, Greatest Common Divisor (GCD) is the largest possible integer, that divides both of the integers. The condition is that the numbers must be non-zero.

We will follow the Euclidean Algorithm to find the GCD of two numbers.

Input and Output

Two numbers 51 and 34
The GCD is: 17


findGCD(a, b)

Input: Two numbers a and b.

Output: GCD of a and b.

   if a = 0 OR b = 0, then
      return 0
   if a = b, then
      return b
   if a > b, then
      return findGCD(a-b, b)
      return findGCD(a, b-a)


using namespace std;

int findGCD(int a, int b) {    //assume a is greater than b
   if(a == 0 || b == 0)
      return 0;    //as a and b are 0, the greatest divisior is also 0
      return b;    //when both numbers are same
      return findGCD(a-b, b);
      return findGCD(a, b-a);

int main() {
   int a, b;
   cout << "Enter Two numbers to find GCD: "; cin >> a >> b;
   cout << "The GCD is: " << findGCD(a,b);


Enter Two numbers to find GCD: 51 34
The GCD is: 17

Monica Mona
Monica Mona

Student of life, and a lifelong learner

Updated on: 17-Jun-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started