C++ Program to Find GCD or HCF of Two Numbers Using Recursion

  • How to find GCD (Greatest Common Divisor) or two numbers using recursion in C++.
  • Write a C++ program to calculate GCD or HCF of two numbers using recursion.

C++ program to calculate GCD using recursion

#include <iostream>

using namespace std;
  
int getGcd(int a, int b);

int main(){
    int num1, num2, gcd;
    
 cout << "Enter two numbers\n";
    cin >> num1 >> num2;
    
    gcd = getGcd(num1, num2);

    cout << "GCD of " << num1 << " and " << num2 << " is " << gcd;

    return 0;
}
/*
 * Function to calculate Greatest Common Divisor of two number
 */
 int getGcd(int a, int b) {
  if (b == 0) {
    return a;
  }
  else {
    return getGcd(b, a % b);
  }
}
Output
Enter two numbers
8 60
GCD of 8 and 60 is 4