Dynamic Programming21 sections · 916 units
Open in Course

Power Function - Implementation

The efficient code

Here is the faster recursive power function:

function power(x, n)
    if n = 0 then
        return 1
    if n is even then
        half := power(x, n / 2)
        return half × half
    return x × power(x, n - 1)

If nn is 00, return 11. If nn is even, compute power(x, n / 2) once, store it, and square it. If nn is odd, multiply xx by power(x, n - 1). Trace power(2, 10): you get power(2, 5) squared. Then power(2, 5) = 22 × power(2, 4). Then power(2, 4) = power(2, 2) squared. Then power(2, 2) = power(2, 1) squared. Then power(2, 1) = 22 × power(2, 0) = 22. Just 66 calls for n=10n = 10.

Time complexity: O(logn)O(\log n).

Space complexity: O(logn)O(\log n) due to the recursive call stack.