Math Fundamentals18 sections · 814 units
Open in Course

Power - Implementation (The code)

Recursive solution

Here's the recursive solution:


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

The base case is n=0n = 0, which returns 11. For negative nn, you flip xx to 1/x1/x and make nn positive. Then you halve nn at each recursive step, giving O(logn)O(\log n) time and O(logn)O(\log n) space for the call stack.