Write a function that takes a decimal number x and a whole number n and returns x to the power n: x multiplied by itself n times. When n is negative the answer is 1 divided by x to the power −n, and any x to the power 0 is 1.
Do not call the language's built-in power function. Answers within 0.000001 of the exact value are accepted.
Example 1
Input: x = 3.0, n = 5 Output: 243.0 Why: 3 · 3 · 3 · 3 · 3 = 243
2 more examples and the constraints
Example 2
Input: x = 2.0, n = -3 Output: 0.125 Why: 1 / 2³ = 1 / 8
Example 3
Input: x = -2.0, n = 3 Output: -8.0 Why: an odd power keeps the minus sign
Constraints
- −100 < x < 100
- −2,147,483,648 ≤ n ≤ 2,147,483,647 (any 32-bit integer)
- x is not 0 when n ≤ 0
- The answer is between −10,000 and 10,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Halve the power, recursivelyO(log n)
- Binary powers, one loopO(log n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for n = 2,147,483,647 | Verdict |
|---|---|---|---|
| Halve the power, recursively | O(log n) | Passes; uses the call stack | |
| Binary powers, one loop | O(log n) | Best; no recursion |
n = the exponent. Multiplying n times would be 2 billion steps; both of these take about 31.
Edge cases to test
- n = −2,147,483,648. Negating it overflows a 32-bit int. Use a 64-bit copy.
- n = 0. The answer is 1 for any non-zero x.
- Negative x. (−2)³ = −8 but (−2)⁴ = 16: the sign follows the parity of n.
- Huge n with x = 1 or −1. The answer is 1 or ±1, and the loop must still end quickly.
- Tiny results. 2 to the power −2³¹ is so small it rounds to 0; that is within the allowed error.
Common mistakes
- Negating n in a 32-bit int, which overflows for the smallest value.
- Calling the half power twice instead of once, which makes the recursion O(n).
- Using
>>in JavaScript or TypeScript on 2³¹, which wraps to a negative number.
How to talk through it
- 1Clarify. Can n be negative? Can x be 0? How close must the answer be?
- 2Give the brute force. Multiply n times; say that n can be about 2 billion, so that is too slow.
- 3Square instead. x to the 2k is (x to the k) squared, so each step halves n: O(log n).
- 4Code the loop. Flip x for negative n using a 64-bit copy, then multiply in x on each 1 bit and square.
- 5Test out loud. Run n = 0, a negative n, the smallest int, and a negative x with an odd power.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?