Pow(x, n)
Table of Contents + β
Pow(x, n) asks you to compute one number raised to a power. It sounds easy. Just multiply in a loop, right? But the interviewer wants the fast version. They also want to see you handle a negative power without breaking. That is where most people slip.
π― The Problem
You get a number x and a whole number n, and return x raised to the power n.
The rules:
- The power
ncan be positive, zero, or negative. - A negative exponent means one divided by the positive power. So
x^-nis1 / x^n. - A power of zero gives
1. - The base
xis a floating point number.
Let us try x = 2.0 and n = 10. That means 2 multiplied by itself ten times. The answer is 1024. If n were -2, the answer would be 1 / (x * x).
Input: x = 2.0, n = 10Output: 1024.0
Explanation: 2 multiplied by itself 10 times is 1024The tricky part is the negative power. A negative exponent means you flip the result. So x^-n is the same as 1 / x^n. We compute the positive power first. Then we take its reciprocal.
Here is the plain idea of raising 2 to the power 10 by simple multiplication.
π’ Approach 1: Repeated Multiply (Brute Force)
The idea:
- Start with a result of
1. - Multiply it by
xa total ofntimes. - After the loop, the result holds
x^n.
How it handles a negative power:
- Compute the positive power the same way.
- Then return
1divided by that.
Why it is weak:
- If
nis one million, you do one million multiplications. - That is O(n) time.
- For large powers it is too slow.
Here is the repeated-multiply code:
def my_pow(x, n): if n < 0: x = 1 / x n = -n
answer = 1 for _ in range(n): answer *= x return answerπ§ Approach 2: Recursive Divide and Conquer (Better)
The idea in one line: x^n is (x^(n/2))^2, so solve half the power and square the result.
How it works:
- Compute
half = x^(n/2)by calling the same function onn/2. - If
nis even, the answer ishalf * half. - If
nis odd, the answer ishalf * half * x, the one extra factor. - The base case is
n = 0, which returns1.
Why it is better:
- Each call halves the power, so the depth is about
log n. - That is O(log n) time, far fewer multiplications than the loop.
Why it is not the top pick:
- The recursion uses a call stack of depth
log n, so space is O(log n). - The loop version below does the same work with O(1) space.
Here is the recursive divide-and-conquer code:
def my_pow(x, n): if n == 0: return 1 if n < 0: return 1 / my_pow(x, -n)
half = my_pow(x, n // 2) if n % 2 == 0: return half * half return half * half * xβ‘ Approach 3: Exponentiation by Squaring, Loop (Best)
The idea in one line: square the base and halve the power each round, peeling off one factor when the power is odd.
How it works:
- This is called exponentiation by squaring.
- Walk while
nis greater than zero. - When the power is odd, multiply the current base into the result.
- Square the base, then halve the power with integer division.
Why it is fast:
- Each round cuts the power in half, so it takes about
log nsteps. - For a power of one million that is around twenty steps, not a million.
- It uses only a few variables, so the space is O(1).
How it handles a negative power:
- Flip
nto positive first and replacexwith1 / x. - At the end the result already has the right sign.
This diagram shows the power being halved each round until it reaches zero.
Steps to Solve
- If
nis negative, setxto1 / xand makenpositive. - Start the result at
1. - While
nis greater than zero, check ifnis odd. - If
nis odd, multiply the result by the current base. - Square the base, and halve
nusing integer division. - When
nreaches zero, return the result.
This Python version flips a negative power, then squares its way up.
def my_pow(x, n): if n < 0: x = 1 / x # negative power means reciprocal n = -n result = 1.0 while n > 0: if n % 2 == 1: # power is odd result *= x # peel off one factor x *= x # square the base n //= 2 # halve the power return result
print(my_pow(2.0, 10))The output of the above code will be:
1024.0Let us walk through the Python version line by line.
if n < 0: x = 1 / x n = -nThis handles the negative power first. A negative exponent means one divided by the positive power. So we flip the base to its reciprocal. Then we make n positive. Now the rest of the code only deals with a positive power. That keeps the loop simple.
result = 1.0We start the answer at 1.0. Anything multiplied by one stays the same. So one is the safe starting point for building up a product.
while n > 0: if n % 2 == 1: result *= x x *= x n //= 2This is the heart of the trick. n % 2 == 1 checks if the power is odd. If it is odd, we multiply the current base into the result. That peels off one factor of x. Then x *= x squares the base. So the base now covers twice the power it did before. And n //= 2 halves the power with integer division. Each round the power gets cut in half. So the loop runs about log n times instead of n times.
return resultWhen n reaches zero, every factor has been folded into result. So we return it. If the power was negative, the reciprocal at the start already took care of the sign.
β±οΈ Time and Space Complexity
The brute force does one multiplication per unit of power, so it is O(n) time. The squaring method halves the power every round, so it runs in O(log n) time. Both use only a few variables, so the space is O(1). The squaring method wins big for large powers.
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Repeated multiply (brute force) | O(n) | O(1) |
| Recursive divide and conquer | O(log n) | O(log n) |
| Exponentiation by squaring (loop) | O(log n) | O(1) |
Tip
Watch the negative power. Copy n into a wider type before you flip its sign. Flipping the smallest possible integer can overflow if you stay in a 32-bit type. Using a long avoids that trap.
π§© Key Takeaways
- β A negative power means one divided by the positive power, so flip the base first.
- β
The brute force multiplies
ntimes, which is slow for large powers. - β Exponentiation by squaring halves the power each round, giving O(log n) time.
- β When the power is odd, peel off one factor into the result, then keep squaring.
- β Copy the power into a wider type before flipping its sign to avoid overflow.
Check Your Knowledge
Test what you learned. Pick an answer for each question, then click Check.
- 1
What does a negative exponent mean for Pow(x, n)?
Why: x^-n equals 1 / x^n, so you compute the positive power and take its reciprocal.
- 2
Why is exponentiation by squaring faster than repeated multiplication?
Why: Each round squares the base and halves the power, giving O(log n) steps instead of O(n).
- 3
In the squaring loop, what happens when the current power is odd?
Why: An odd power means one extra factor of the base must be folded into the result before squaring.
- 4
Why copy n into a long before flipping its sign?
Why: The most negative 32-bit value has no positive partner in 32 bits, so a wider type avoids overflow.