Python Program to Find HCF of Two Numbers
while b != 0: a, b = b, a % b and then a will be the HCF.Examples
How to Think About It
Algorithm
Code
def find_hcf(a, b): while b != 0: a, b = b, a % b return a num1 = 12 num2 = 15 print("HCF of", num1, "and", num2, "is", find_hcf(num1, num2))
Dry Run
Let's trace the example where a=12 and b=15 through the code.
Initial values
a = 12, b = 15
First iteration
a, b = b, a % b → a = 15, b = 12 % 15 = 12
Second iteration
a, b = b, a % b → a = 12, b = 15 % 12 = 3
Third iteration
a, b = b, a % b → a = 3, b = 12 % 3 = 0
End loop
b is 0, so return a = 3
| a | b |
|---|---|
| 12 | 15 |
| 15 | 12 |
| 12 | 3 |
| 3 | 0 |
Why This Works
Step 1: Why use remainder?
The HCF of two numbers also divides their remainder, so replacing the larger number by the remainder keeps the HCF unchanged.
Step 2: Loop until remainder zero
We repeat the process until the remainder becomes zero, meaning the smaller number at that point is the HCF.
Step 3: Return the HCF
When the remainder is zero, the other number is the highest common factor of the original two numbers.
Alternative Approaches
import math num1 = 12 num2 = 15 print("HCF of", num1, "and", num2, "is", math.gcd(num1, num2))
def find_hcf_sub(a, b): while a != b: if a > b: a -= b else: b -= a return a print(find_hcf_sub(12, 15))
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?
Using Python's built-in math.gcd is fastest and simplest, followed by the Euclidean algorithm with modulo. The subtraction method is slower and less efficient.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Euclidean algorithm (modulo) | O(log(min(a,b))) | O(1) | General use, efficient for all sizes |
| math.gcd function | O(log(min(a,b))) | O(1) | Quickest and simplest in Python |
| Subtraction method | O(min(a,b)) | O(1) | Educational, but inefficient for large numbers |