Problem Description
Implement a function to calculate x raised to the power n (i.e., x^n). This function must handle both positive and negative exponents, while ensuring an efficient solution even for large values of n.
Key Insights
- Use exponentiation by squaring to reduce the number of multiplications.
- For a negative exponent, compute the power for |n| and then take the reciprocal.
- Handle the edge case when n is 0 (return 1).
- The algorithm works in O(log n) time complexity.
Space and Time Complexity
Time Complexity: O(log |n|)
Space Complexity: O(1) for the iterative solution, or O(log |n|) if implemented recursively
Solution
We use exponentiation by squaring, an algorithm that reduces the number of multiplications by repeatedly squaring the base and halving the exponent. Here's how it works:
- If n is negative, switch x to 1/x and n to -n.
- Initialize the result as 1.
- Loop while n is greater than 0:
- If the current n is odd, multiply the result by x.
- Square the base x.
- Divide n by 2 (using integer division). This iterative approach efficiently computes the power in logarithmic steps. The same approach can be implemented recursively.