๐ Day 40/150 – Find HCF of Two Numbers in Python
HCF (Highest Common Factor) is the greatest number that divides two numbers exactly.
Examples:
HCF of 12 and 18 = 6
HCF of 20 and 30 = 10
It is also called GCD (Greatest Common Divisor).
Let’s explore different ways to find HCF in Python ๐
๐น Method 1 – Using for Loop
✅ Simple beginner-friendly method.
๐น Method 2 – Taking User Input
a = int(input("Enter first number: ")) b = int(input("Enter second number: ")) hcf = 1 for i in range(1, min(a, b) + 1): if a % i == 0 and b % i == 0: hcf = i print("HCF:", hcf)
✅ Useful for dynamic programs.
๐น Method 3 – Using Euclidean Algorithm
✅ Fastest and most efficient method.
๐น Method 4 – Using Function
def hcf(a, b): while b != 0: a, b = b, a % b return a print(hcf(12, 18))
✅ Clean and reusable.
๐ฏ Output
HCF: 6
๐ Key Takeaways
- HCF = greatest common divisor of two numbers.
- Use % to check common factors.
- Euclidean algorithm is fastest.
- math.gcd() is built-in shortcut.


