DEV Community

Cover image for Computing power
hebaShakeel
hebaShakeel

Posted on

Computing power

Ok so your interviewer asks you write a function to find the power of a number. We have all used Math.pow() in JAVA, pow() function in C/C++, but have you wondered how to compute the power without using these????

Let's find out.

Example:
x = 2
y = 3
Output = 8 ( 2 to the power 3 = 2 *2 *2)

Naive Solution: Time Complexity = O(n)
Image description

Output:
Image description

Recursive Solution:
Time Complexity = θ(logn)
Space Complexity = θ(logn)
Image description

Output:
Image description

It has recursive function calls which will take space in function call stack. It also has overhead for function call in return.

Can you think of a better solution?
How about an Iterative solution?
Do share your views in the comments.

Discussion (0)