Dynamic Programming21 sections · 916 units
Open in Course

Power Function - Problem Statement

Computing x^n

Given a number xx and a non-negative integer nn, compute xnx^n. For example, 210=10242^{10} = 1024 and 34=813^4 = 81. You could multiply xx by itself nn times. That takes nn multiplications.

But there is a recursive approach that uses far fewer operations. Notice that x10=(x5)2x^{10} = (x^5)^2. Can you see what x10x^{10} and x5x^5 have in common? Squaring xn/2x^{n/2} halves the remaining exponent each step, so the answer arrives in O(logn)O(\log n) multiplications.