Combinatorics: count without generating
Picture
Choosing 2 people from 5 gives 10 groups. Arranging 2 roles from 5 gives 20 ordered assignments.
Predict
Does C(n,k) distinguish the order of selected items?
Walk through the small example
No. A multiplicative recurrence preserves integrality and avoids factorial-sized intermediate work.
Mental model and complete Python solution
Before writing a formula, describe one outcome and ask what changes make it a different outcome. The algebra comes after that identity decision.
What the function promises: Return C(n,k) for integers n>=0. Invalid k returns zero.
def choose(n, k):
if n < 0: raise ValueError("Negative n")
if k < 0 or k > n: return 0
k = min(k, n-k)
answer = 1
for i in range(1, k+1):
answer = answer * (n-k+i) // i
return answer
assert choose(5,2) == 10
assert choose(100,0) == 1
assert choose(4,7) == 0
Work and storage: O(min(k,n−k)) arithmetic steps and O(1) stored integers; big-integer cost depends on result size.
When to recognize it: A multiplicative recurrence preserves integrality and avoids factorial-sized intermediate work.
Check before applying it: A memorized formula fails when objects repeat or constraints couple choices.
Change one rule
Need C(n,k) modulo a composite number.
See what changes
Modular inverses may not exist; use prime-factor exponents, CRT, or modulus-specific methods.
Connect
cost: Counting the output space explains why enumeration may be impossible.
Probability DP: add disjoint outcomes: Binomial counts become probabilities after weighting outcomes.