
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 using 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
- Related Questions & Answers
- Program to find GCD or HCF of two numbers in C++
- Program to find GCD or HCF of two numbers using Middle School Procedure in C++
- Java program to find the GCD or HCF of two numbers
- C++ Program to Find GCD of Two Numbers Using Recursive Euclid Algorithm
- Python Program to Find the Product of two Numbers Using Recursion
- Java Program to Find the Product of Two Numbers Using Recursion
- C Program to find sum of two numbers without using any operator
- How to Find HCF or GCD using Python?
- Finding LCM of more than two (or array) numbers without using GCD in C++
- Find the Sum of two Binary Numbers without using a method in C#?
- C++ Program to Implement Extended Euclidean Algorithm
- C++ Program to Find Fibonacci Numbers using Recursion
- C++ program to Find Sum of Natural Numbers using Recursion
- How do I add two numbers without using ++ or + or any other arithmetic operator in C/C++?
- Program to find HCF (Highest Common Factor) of 2 Numbers in C++
Advertisements