Pow(x, n)
Difficulty: Medium
Compute x^n (a number x raised to an integer power n) without a built-in power function.
n can be negative, in which case x^n means 1 / x^(-n).
Examples
Input: x = 2.0, n = 10
Output: 1024.0
2 multiplied by itself 10 times.
Input: x = 2.1, n = 3
Output: 9.261
2.1 * 2.1 * 2.1 = 9.261.
Input: x = 2.0, n = -2
Output: 0.25
x^-2 means 1 / x^2 = 1 / 4 = 0.25.
Constraints
-100 < x < 100
-2^31 <= n <= 2^31 - 1
x != 0, or n > 0
n can be negative
Approach
The direct approach multiplies x by itself n times in a loop. That's n multiplications, which is slow when n is large (say, in the billions).
A faster approach reuses work. If you know x^(n/2), square it to get x^n, with one extra factor of x when n is odd. Repeating this halves the exponent at each step instead of reducing it by one, so you need only about log2(n) multiplications. Handle a negative n up front by using 1/x and a positive exponent.
Solutions
Brute Force - Repeated Multiplication
For a negative exponent, flip x to 1/x and make n positive. Then multiply x into a running result n times.
function myPow(x, n) {
if (n < 0) {
x = 1 / x;
n = -n;
}
let result = 1;
for (let i = 0; i < n; i++) {
result *= x;
}
return result;
}Time: O(n) · Space: O(1)
Optimal - Fast (Binary) Exponentiation
Handle a negative exponent as before. Then recurse: find x^(n/2), square it, and multiply by one extra x if n is odd. Each call halves the exponent instead of reducing it by one.
function myPow(x, n) {
if (n < 0) {
x = 1 / x;
n = -n;
}
return fastPow(x, n);
}
function fastPow(x, n) {
if (n === 0) return 1;
const half = fastPow(x, Math.floor(n / 2));
const halfSquared = half * half;
return n % 2 === 0 ? halfSquared : halfSquared * x;
}Time: O(log n) · Space: O(log n), for the recursion stack