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 is , return . If is even, compute power(x, n / 2) once, store it, and square it. If is odd, multiply by power(x, n - 1). Trace power(2, 10): you get power(2, 5) squared. Then power(2, 5) = × power(2, 4). Then power(2, 4) = power(2, 2) squared. Then power(2, 2) = power(2, 1) squared. Then power(2, 1) = × power(2, 0) = . Just calls for .
Time complexity: .
Space complexity: due to the recursive call stack.