Dynamic Programming21 sections · 916 units
Open in Course

Power Function - Naive Recursion

The slow way

The obvious recursive formula is xn=x×xn1x^n = x \times x^{n-1}. Base case: x0=1x^0 = 1. This is correct and simple. To compute x10x^{10}, you compute x9x^9 and multiply by xx. To compute x9x^9, you compute x8x^8 and multiply by xx. And so on.

This works, but it makes nn recursive calls. For x1000x^{1000}, that is 10001000 calls. Can you do better? Take time to work through examples. Notice what happens when nn is even: x10=(x5)2x^{10} = (x^5)^2.