50. Pow(x, n) - Explanation
Description
Pow(x, n) is a mathematical function to calculate the value of x raised to the power of n (i.e., x^n).
Given a floating-point value x and an integer value n, implement the myPow(x, n) function, which calculates x raised to the power n.
You may not use any built-in library functions.
Example 1:
Input: x = 2.00000, n = 5
Output: 32.00000Example 2:
Input: x = 1.10000, n = 10
Output: 2.59374Example 3:
Input: x = 2.00000, n = -3
Output: 0.12500Constraints:
-100.0 < x < 100.0-1000 <= n <= 1000nis an integer.- If
x = 0, thennwill be positive.
Topics
Recommended Time & Space Complexity
You should aim for a solution as good or better than O(logn) time and O(logn) space, where n is the given integer.
Hint 1
A brute force approach would be to iterate linearly up to n, multiplying by x each time to find (x^n). If n is negative, return (1 / (x^n)); otherwise, return (x^n). Can you think of a better way? Maybe a recursive approach would be more efficient.
Hint 2
For example, to calculate 2^6, instead of multiplying 2 six times, we compute 2^3 and square the result. The same logic applies recursively to find 2^3 and further break down the multiplication. What should be the base case for this recursion? Maybe you should consider the term that cannot be further broken down.
Hint 3
In (x^n), if x is 0, we return 0. If n is 0, we return 1, as any number raised to the power of 0 is 1. Otherwise, we compute (x^(n/2)) recursively and square the result. If n is odd, we multiply the final result by x. What should be the logic if n is negative?
Hint 4
We start the recursion with the absolute value of n. After computing the result as res, we return res if n is non-negative; otherwise, we return (1 / res).
Prerequisites
Before attempting this problem, you should be comfortable with:
- Recursion and Divide-and-Conquer - Breaking a problem in half repeatedly to reduce complexity
- Binary Exponentiation - The mathematical property that x^n = (x^2)^(n/2) for even n
- Bit Manipulation Basics - Using bitwise AND and right shift to check odd/even and halve values
- Handling Edge Cases - Managing negative exponents and integer overflow when negating values
1. Brute Force
Intuition
We are asked to compute ( x^n ), where:
xis a floating-point numberncan be positive, zero, or negative
The most straightforward way to think about exponentiation is:
- multiplying
xby itselfntimes
This brute force approach directly follows the mathematical definition of power:
- if
nis positive → multiplyxrepeatedly - if
nis zero → the result is always1 - if
nis negative → compute ( x^{|n|} ) and take its reciprocal
Although this method is not efficient for large n, it is very easy to understand and is a good starting point.
Algorithm
- Handle edge cases:
- If
x == 0, return0 - If
n == 0, return1
- If
- Initialize
res = 1to store the result. - Repeat
abs(n)times:- multiply
resbyx
- multiply
- If
nis positive:- return
res
- return
- If
nis negative:- return
1 / res
- return
Time & Space Complexity
- Time complexity:
- Space complexity:
2. Binary Exponentiation (Recursive)
Intuition
Computing ( x^n ) by multiplying x repeatedly works, but it becomes very slow when n is large.
A much better idea is to use binary exponentiation, which is based on these observations:
- If
nis even:- ( x^n = (x^2)^{n/2} )
- If
nis odd:- ( x^n = x \times (x^2)^{(n-1)/2} )
This means we can:
- halve the exponent at each step
- square the base accordingly
By doing this recursively, the number of multiplications reduces from O(n) to O(log n).
We also handle negative powers by:
- computing ( x^{|n|} )
- taking the reciprocal if
nis negative
Algorithm
- Define a recursive helper function
helper(x, n):- If
x == 0, return0 - If
n == 0, return1
- If
- Recursively compute:
res = helper(x * x, n // 2)
- If
nis odd:- return
x * res
- return
- If
nis even:- return
res
- return
- Call
helper(x, abs(n))to compute the magnitude. - If
nis negative:- return
1 / result
- return
- Otherwise:
- return
result
- return
Time & Space Complexity
- Time complexity:
- Space complexity: for recursion stack.
3. Binary Exponentiation (Iterative)
Intuition
We want to compute ( x^n ) efficiently, even when n is very large (positive or negative).
The brute force approach multiplies x repeatedly and takes O(n) time, which is too slow.
Instead, we use binary exponentiation, which reduces the time complexity to O(log n).
The key ideas are:
- Any number
ncan be written in binary - If the current
poweris odd, we must include one extraxin the result - We repeatedly:
- square the base (
x = x * x) - halve the exponent (
power = power // 2)
- square the base (
For negative powers:
- ( x^n = \frac{1}{x^{|n|}} )
- so we compute using
abs(n)and take the reciprocal at the end if needed
This iterative version avoids recursion and works efficiently with constant extra space.
Algorithm
- Handle edge cases:
- If
x == 0, return0 - If
n == 0, return1
- If
- Initialize:
res = 1(stores the final answer)power = abs(n)(work with positive exponent)
- While
power > 0:- If
poweris odd:- multiply
resbyx
- multiply
- Square the base:
x = x * x
- Divide the exponent by 2:
power = power >> 1
- If
- If
nis negative:- return
1 / res
- return
- Otherwise:
- return
res
- return
Time & Space Complexity
- Time complexity:
- Space complexity:
Common Pitfalls
Integer Overflow When Negating n
When n is Integer.MIN_VALUE (-2147483648), computing abs(n) or -n overflows because the positive equivalent exceeds Integer.MAX_VALUE. Always cast to a long before taking the absolute value to avoid this undefined behavior.
Forgetting to Handle Negative Exponents
A negative exponent means the result is 1 / x^|n|. Omitting this reciprocal step returns the wrong answer for all negative n values. Compute the power using the absolute value, then invert if n was negative.
Using Brute Force for Large Exponents
Multiplying x by itself n times works but times out for large n (e.g., n = 2^31 - 1). Binary exponentiation reduces the number of operations from O(n) to O(log n) by squaring the base and halving the exponent at each step.
Sign in to join the discussion