nCr Recursively (Pascal Formula)
Calculate nCr using Pascal triangle formula recursively.
AdvancedPhase 3 - Level 2: Advanced RecursionExample 10 of 10
ncr-recursively-pascal-formula.py
1def ncr(n, r):2 # Base cases3 if r == 0 or r == n:4 return 15 if r > n:6 return 078 # Recursive case (Pascal's formula)9 return ncr(n - 1, r - 1) + ncr(n - 1, r)1011# Test12n = int(input("Enter n: "))13r = int(input("Enter r: "))14result = ncr(n, r)15print(f"{n}C{r} = {result}")
Output
Enter n: 5 Enter r: 2 5C2 = 10
What's going on
Pascal's formula: nCr = (n-1)C(r-1) + (n-1)Cr.
Key Concepts:
Base cases: nC0 = nCn = 1
Recursive: sum of two combinations
Uses Pascal triangle property
🔗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