Dynamic Programming21 sections · 916 units
Open in Course

Power Function - Walkthrough

Tracing fast exponentiation

Let me trace power(22, 1010):

Call 11: power(22, 1010) \rightarrow 1010 is even, so compute power(22, 55) and square it Call 22: power(22, 55) \rightarrow 55 is odd, so return 2×2 \times power(22, 44)

Call 33: power(22, 44) \rightarrow 44 is even, so compute power(22, 22) and square it Call 44: power(22, 22) \rightarrow 22 is even, so compute power(22, 11) and square it Call 55: power(22, 11) \rightarrow 11 is odd, so return 2×2 \times power(22, 00)

Call 66: power(22, 00) hits base case, returns 11

Then the results come back: 2×1=22 \times 1 = 2, 22=42^2 = 4, 42=164^2 = 16, 2×16=322 \times 16 = 32, 322=102432^2 = 1024. Only 66 calls instead of 1010 multiplications.