Program to find HCF (Highest Common Factor) of 2 Numbers in C++

C++Server Side ProgrammingProgramming

In this tutorial, we will be discussing a program to find HCF (highest common factor) of two numbers.

For this we will be provided with two numbers. Our task is to find the highest common factor (HCF) of those numbers and return it.

Example

 Live Demo

#include <stdio.h>
//recursive call to find HCF
int gcd(int a, int b){
   if (a == 0 || b == 0)
      return 0;
   if (a == b)
      return a;
   if (a > b)
      return gcd(a-b, b);
   return gcd(a, b-a);
}
int main(){
   int a = 98, b = 56;
   printf("GCD of %d and %d is %d ", a, b, gcd(a, b));
   return 0;
}

Output

GCD of 98 and 56 is 14
raja
Published on 09-Sep-2020 11:47:35
Advertisements