C++ Program to Find HCF of Two Numbers
while(b != 0) { int temp = b; b = a % b; a = temp; } where a and b are the input numbers.Examples
How to Think About It
Algorithm
Code
#include <iostream> using namespace std; int main() { int a, b; cout << "Enter two numbers: "; cin >> a >> b; while (b != 0) { int temp = b; b = a % b; a = temp; } cout << "HCF is " << a << endl; return 0; }
Dry Run
Let's trace the input a=12, b=18 through the code
Initial values
a = 12, b = 18
First iteration
temp = 18; b = 12 % 18 = 12; a = 18
Second iteration
temp = 12; b = 18 % 12 = 6; a = 12
Third iteration
temp = 6; b = 12 % 6 = 0; a = 6
Loop ends
b is 0, so HCF is a = 6
| a | b | temp | b = a % b |
|---|---|---|---|
| 12 | 18 | ||
| 18 | 12 | 18 | 12 |
| 12 | 6 | 12 | 6 |
| 6 | 0 | 6 | 0 |
Why This Works
Step 1: Why use the Euclidean algorithm?
The Euclidean algorithm efficiently finds the HCF by using the remainder operation % to reduce the problem size each step.
Step 2: How the loop works
Each loop iteration replaces the pair (a, b) with (b, a % b), moving closer to the HCF.
Step 3: When the loop ends
When b becomes zero, a holds the HCF because the remainder is zero, meaning a divides the original numbers.
Alternative Approaches
#include <iostream> using namespace std; int hcf(int a, int b) { if (b == 0) return a; return hcf(b, a % b); } int main() { int a, b; cout << "Enter two numbers: "; cin >> a >> b; cout << "HCF is " << hcf(a, b) << endl; return 0; }
#include <iostream> using namespace std; int main() { int a, b, hcf = 1; cout << "Enter two numbers: "; cin >> a >> b; int min = (a < b) ? a : b; for (int i = 1; i <= min; i++) { if (a % i == 0 && b % i == 0) { hcf = i; } } cout << "HCF is " << hcf << endl; return 0; }
Complexity: O(log(min(a, b))) time, O(1) space
Time Complexity
The Euclidean algorithm runs in logarithmic time relative to the smaller input because each step reduces the problem size significantly.
Space Complexity
It uses constant extra space since it only stores a few variables and updates them in place.
Which Approach is Fastest?
The iterative Euclidean algorithm is fastest and most memory efficient compared to recursion or brute force.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Iterative Euclidean | O(log(min(a,b))) | O(1) | Large numbers, efficiency |
| Recursive Euclidean | O(log(min(a,b))) | O(log(min(a,b))) | Cleaner code, small inputs |
| Brute Force | O(min(a,b)) | O(1) | Very small numbers, simplicity |