Table of Contents
Open Table of Contents
Description
Implement the function pow(x, n), which calculates x raised to the power n (i.e., ).
Example 1:
Input: x = 2.00000, n = 10
Output: 1024.00000
Example 2:
Input: x = 2.10000, n = 3
Output: 9.26100
Example 3:
Input: x = 2.00000, n = -2
Output: 0.25000
Explanation:
Approach
We can use Exponentiation by Squaring to compute efficiently. Instead of multiplying by itself times, we recursively break down the problem:
-
If is even, we can write:
For example, .
-
If is odd, we use:
For example, .
-
If , we compute the reciprocal:
This recursive approach reduces the number of multiplications and handles both positive and negative exponents. By halving the exponent at each step, the algorithm achieves logarithmic time complexity.
Solution
/**
* @param {number} x
* @param {number} n
* @return {number}
*/
var myPow = function (x, n) {
// Base case: any number to the power 0 is 1
if (n === 0) return 1;
// Base case: power of 1 returns the base itself
if (n === 1) return x;
// Base case: power of -1 returns the reciprocal of the base
if (n === -1) return 1 / x;
const currentProduct = n % 2 ? x : 1;
// Recursive call: square the base and halve the exponent (floor division)
// Multiply by currentProduct if n is odd
return currentProduct * myPow(x * x, Math.floor(n / 2)) || 0;
};
Complexity Analysis
Time Complexity
The time complexity is , because each recursive (or iterative) step halves the exponent, resulting in logarithmic growth with respect to .
Space Complexity
The space complexity is for the recursive approach, due to the call stack depth. If implemented iteratively, the space complexity is .