Java Program to Find HCF of Two Numbers
while(b != 0) { int temp = b; b = a % b; a = temp; } where a ends as the HCF.Examples
How to Think About It
Algorithm
Code
public class HCF { public static void main(String[] args) { int a = 12, b = 18; while (b != 0) { int temp = b; b = a % b; a = temp; } System.out.println("HCF is " + a); } }
Dry Run
Let's trace the example where a=12 and 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 | a % b |
|---|---|---|---|
| 12 | 18 | - | - |
| 18 | 12 | 18 | 12 |
| 12 | 6 | 12 | 6 |
| 6 | 0 | 6 | 0 |
Why This Works
Step 1: Using the Euclidean algorithm
The code uses the Euclidean algorithm which finds the HCF by repeatedly replacing the larger number with the remainder of dividing the two numbers.
Step 2: Loop until remainder is zero
The loop continues until the remainder (b) becomes zero, meaning the last non-zero remainder (a) is the HCF.
Step 3: Final result
When the loop ends, the variable a holds the highest common factor of the two input numbers.
Alternative Approaches
public class HCF { public static int findHCF(int a, int b) { if (b == 0) return a; return findHCF(b, a % b); } public static void main(String[] args) { System.out.println("HCF is " + findHCF(12, 18)); } }
public class HCF { public static int findHCF(int a, int b) { while (a != b) { if (a > b) a = a - b; else b = b - a; } return a; } public static void main(String[] args) { System.out.println("HCF is " + findHCF(12, 18)); } }
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 since it only stores a few variables and updates them in place.
Which Approach is Fastest?
The modulo-based Euclidean algorithm is faster and more efficient than the subtraction method and safer than recursion for large inputs.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Modulo Euclidean Algorithm | O(log(min(a,b))) | O(1) | General use, large numbers |
| Recursive Euclidean Algorithm | O(log(min(a,b))) | O(log(min(a,b))) | Clean code, small inputs |
| Subtraction Method | O(min(a,b)) | O(1) | Simple understanding, small numbers |