
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find HCF of Two Numbers Without Recursion or Euclidean Algorithm in C++
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
#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
Advertisements