I have the following code for calculating x^n:
def power(x, n):
if n == 0:
return 1
if n == 1:
return x
d = n//2
return power(x, d) * power(x, n-d)
I want to determine the space and time complexity for this code.
time complexity: (my analysis)
- At each level x the function calls itself 2^x times.
- Since we are dividing n by 2 at each level, there will be logn levels (logn+1 in case n is odd) (log is of base 2)
- So, total number of function calls will be 2^0 + 2^1 + 2^2 + ... + 2^logn.
- Each function call will do some k constant work.
I don't know how to simplify this to determine big O.
space complexity: (my analysis)
- At max, there will be logn + 1(in case of odd n) function calls in stack at a given time.
- So, space complexity will be O(logn).
Need help in determining the time complexity and verifying space complexity.