Find HCF (GCD) Using Loops
Find HCF/GCD of two numbers using loops.
IntermediatePhase 2 - Level 3: Mathematical & Logical PatternsExample 4 of 13
find-hcf-gcd-using-loops.py
1# Take two numbers2a = int(input("Enter first number: "))3b = int(input("Enter second number: "))45# Find GCD6gcd = 17smaller = min(a, b)89for i in range(1, smaller + 1):10 if a % i == 0 and b % i == 0:11 gcd = i1213print(f"GCD of {a} and {b} is {gcd}")
Output
Enter first number: 48 Enter second number: 18 GCD of 48 and 18 is 6
What's going on
Find largest number that divides both.
Key Concepts:
Check numbers from 1 to smaller number
If divides both, update GCD
Largest common divisor is the answer
🔗Related Content
- 📖
Phase 2 - Learn Concepts
Review Phase 2 concepts and explanations
- 📝
Phase 2 - Quiz
Test your Phase 2 understanding with quiz questions
- 💻
Phase 2 - All Practice Problems
Explore all practice problems for Phase 2
- 🎓
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- 🧠
Logic Building Overview
Learn about the complete logic building curriculum