gcd of two numbers using function in c++ code example

Example 1: greatest common denominator recursion c++

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

Example 2: gcd of two numbers c++

// gcd function definition below:
int gcd(int a, int b) {
   if (b == 0)
   return a;
   return gcd(b, a % b);
}

int a = 105, b = 30;
cout<<"GCD of "<< a <<" and "<< b <<" is "<< gcd(a, b);
// output = "GCD of 105 and 30 is 15";

Tags:

Cpp Example