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

In the previous article, we have discussed C++ Program to Find Sum of Natural Numbers Using Recursion. In this article, we will see C++ Program to Find GCD or HCF of Two Numbers Using Recursion.

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

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

Exploring basic to advanced concepts in the C++ programming language helps beginners and experienced programmers to excel in C++ Programs. Go with this page & enhance your coding skills.