Find HCF of two numbers without using recursion or Euclidean algorithm in C++

C++Server Side ProgrammingProgramming

As we know, the HCF or GCD can be calculated easily using the Euclidean Algorithm. But here we will see how to generate GCD or HCF without using the Euclidean Algorithm, or any recursive algorithm. Suppose two numbers are present as 16 and 24. The GCD of these two is 8.

Here the approach is simple. If the greater number of these two is divisible by the smaller one, then that is the HCF, otherwise starting from (smaller / 2) to 1, if the current element divides both the number, then that is the HCF.

Example

 Live Demo

#include <iostream>
using namespace std;
int gcd(int a, int b) {
   int min_num = min(a, b);
   if (a % min_num == 0 && b % min_num == 0)
   return min_num;
   for (int i = min_num / 2; i >= 2; i--) {
      if (a % i == 0 && b % i == 0)
      return i;
   }
   return 1;
}
int main() {
   int a = 16, b = 24;
   cout << "HCF: "<< gcd(a, b);
}

Output

HCF: 8
raja
Published on 21-Oct-2019 07:42:40
Advertisements