Exercise 16 of 30 · intermediate · recursion · logarithmic · recurrences
Recursion on half the input
The code
def depth(n):
if n <= 1:
return 0
return 1 + depth(n // 2)Solve T(n) = T(n/2) + O(1).
Count: calls.
Measured counts
Table
| n | count |
|---|---|
| 8 | 4 |
| 16 | 5 |
| 32 | 6 |
| 64 | 7 |
| 128 | 8 |
| 256 | 9 |
| 512 | 10 |
| 1024 | 11 |
| 2048 | 12 |
| 4096 | 13 |
Try to name the class from the shape before opening the answer.
Show the answer and derivation
- Time
- Θ(log n)
- Extra space
- Θ(log n) stack
- Exact count
- ⌊log₂ n⌋ + 1 calls
- Each call halves n and does constant work.
- The recursion bottoms out after ⌊log₂ n⌋ halvings.
- Binary search written recursively has exactly this shape.
Common mistake: Forgetting the stack: the iterative version is O(1) space, the recursive one Θ(log n).
Check: measured count ÷ (log n) settles near 1.08 for large n.