Implement pow(x, n), which calculates x raised to the power n (i.e., xn).
Input: x = 2.00000, n = 10
Output: 1024.00000
Input: x = 2.10000, n = 3
Output: 9.26100
Input: x = 2.00000, n = -2
Output: 0.25000
Explanation: 2-2 = 1/22 = 1/4 = 0.25
The simplest way to calculate x^n is to multiply x by itself n times. While this approach is straightforward, it's very inefficient for large values of n due to its linear complexity. Also, handling negative powers involves taking the reciprocal of positive power results.
n times.The key observation is that x^n can be broken down recursively:
n is even, x^n = x^(n/2) * x^(n/2)n is odd, x^n = x * x^(n//2) * x^(n//2)This approach divides the problem size by half at each step, leading to a more efficient solution.
n at each call.The iterative method of binary exponentiation is similar to the recursive method, but it avoids the overhead of recursion. We use bit manipulation to quickly determine if the current power n is odd and needs additional multiplication by x. This results in efficient exponentiation with reduced time complexity.