C# Program to Find HCF of Two Numbers
while(b != 0) { int temp = b; b = a % b; a = temp; } which returns a as the HCF.Examples
How to Think About It
Algorithm
Code
using System; class Program { static void Main() { int a = 12, b = 18; while (b != 0) { int temp = b; b = a % b; a = temp; } Console.WriteLine("HCF is " + a); } }
Dry Run
Let's trace the example 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 = a = 6
| a | b | temp | b after modulo |
|---|---|---|---|
| 12 | 18 | 18 | 12 |
| 18 | 12 | 12 | 6 |
| 12 | 6 | 6 | 0 |
Why This Works
Step 1: Using Euclidean Algorithm
The code uses the Euclidean algorithm which finds HCF by repeatedly replacing the larger number with the remainder of dividing the larger by the smaller.
Step 2: Loop until remainder zero
The loop continues until the remainder (b) becomes zero, meaning the last non-zero remainder is the HCF.
Step 3: Return the HCF
When the loop ends, the variable a holds the HCF which is printed as the result.
Alternative Approaches
using System; class Program { static int HCF(int a, int b) { if (b == 0) return a; return HCF(b, a % b); } static void Main() { Console.WriteLine("HCF is " + HCF(12, 18)); } }
using System; class Program { static void Main() { int a = 12, b = 18, hcf = 1; int min = a < b ? a : b; for (int i = 1; i <= min; i++) { if (a % i == 0 && b % i == 0) hcf = i; } Console.WriteLine("HCF is " + hcf); } }
Complexity: O(log(min(a,b))) time, O(1) space
Time Complexity
The Euclidean algorithm runs in logarithmic time relative to the smaller input number because each step reduces the problem size significantly.
Space Complexity
The algorithm uses constant extra space as it only stores a few variables and updates them in place.
Which Approach is Fastest?
The Euclidean algorithm (iterative or recursive) is much faster than checking all divisors, especially for large numbers.
| 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))) | Clean code, small inputs |
| Divisor Checking | O(min(a,b)) | O(1) | Small numbers, simplicity |