Dynamic Programming21 sections · 916 units
Open in Course

Power Function - The Optimization

Halving the problem

Here is the trick: x10=(x5)2x^{10} = (x^5)^2. Instead of 1010 multiplications, compute x5x^5 once and square it. More generally: if nn is even, xn=(xn/2)2x^n = (x^{n/2})^2. If nn is odd, xn=x×xn1x^n = x \times x^{n-1}. This cuts the problem size in half each time (when nn is even).

Instead of O(n)O(n) calls, you make O(logn)O(\log n) calls. For n=1000n = 1000, that is 1616 calls instead of 10001000. Huge difference. This improvement reduces redundant work largely.