Calculating HCF By Recursion in C++

Exercise:

Write a C++ program that uses recursive function to calculate GCD of a number.

Click Here to View the Solution:
#include <iostream> 
using namespace std;
int HCF(int num1, int num2);
int main()
{
   int num1, num2;
   cout << "Insert any two positive numbers:\n";
   cin >> num1 >> num2;
   cout << "HCF of " << num1 << " and " <<  num2 << " is: " << HCF(num1, num2);
   return 0;
}
int HCF(int num1, int num2)
{
    if (num2 != 0)
    return HCF(num2, num1 % num2);
    else 
    return num1;
}
Click Here to View the Output:
Insert any two positive numbers:
 64
 36
 HCF of 64 and 36 is: 4
Click Here to View the Explanation:
  • This program uses HCF () function. The bigger number num2 is picked and the HCF (num2, num1 % num2) is applied on it.
  • Through recursion, the number decrements by 1. All numbers are checked 1 by 1. The iterations continue until the number reaches 0.
  • Output is printed.
%d bloggers like this: