GCD Recursively
Find GCD using Euclidean algorithm recursively.
IntermediatePhase 3 - Level 2: Advanced RecursionExample 5 of 10
gcd-recursively.py
1def gcd(a, b):2 # Base case3 if b == 0:4 return a56 # Recursive case (Euclidean algorithm)7 return gcd(b, a % b)89# Test10a = int(input("Enter first number: "))11b = int(input("Enter second number: "))12result = gcd(abs(a), abs(b))13print(f"GCD: {result}")
Output
Enter first number: 48 Enter second number: 18 GCD: 6
What's going on
Euclidean algorithm: GCD(a,b) = GCD(b, a%b).
Key Concepts:
Base case: b == 0, answer is a
Recursive: GCD(b, a % b)
Continues until remainder is 0
🔗Related Content
- 📖
Phase 3 - Learn Concepts
Review Phase 3 concepts and explanations
- 📝
Phase 3 - Quiz
Test your Phase 3 understanding with quiz questions
- 💻
Phase 3 - All Practice Problems
Explore all practice problems for Phase 3
- 🎓
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- 🧠
Logic Building Overview
Learn about the complete logic building curriculum