
Sponsored
Sponsored
The iterative method with exponentiation by squaring is an efficient way to calculate powers. It reduces the time complexity by squaring the base and halving the power at each step. This method leverages the mathematical property that xn = (x2)n/2 when n is even and xn = x * xn - 1 when n is odd. By iteratively updating the base and reducing the power, this method achieves a logarithmic time complexity.
Time Complexity: O(log n), Space Complexity: O(1)
1function myPow(x, n) {
2 let N = n;
3 if (N < 0) {
4 x = 1 / x;
5 N = -N;
6 }
7 let result = 1;
8 while (N !== 0) {
9 if (N % 2 !== 0) {
10 result *= x;
11 }
12 x *= x;
13 N = Math.floor(N / 2);
14 }
15 return result;
16}
17
18console.log(myPow(2.00000, 10));
19console.log(myPow(2.10000, 3));
20console.log(myPow(2.00000, -2));JavaScript handles large integers and floating-point operations natively. This solution uses the same iterative squaring approach with floored division and adjustment for negative powers, ensuring precision during multiplications.
The recursive divide and conquer method further optimizes power calculation by dividing the problem into smaller subproblems. By recursively dividing the power by 2, this approach minimizes the number of multiplications. If the power is even, it computes (xn/2)2, and if odd, it adjusts with an additional multiplication. This recursive approach can be more intuitive, especially for understanding the problem breakdown.
Time Complexity: O(log n), Space Complexity: O(log n) due to the call stack
1
The C recursive solution utilizes a helper function to perform the divide and conquer. The base case is when n equals zero, returning 1. Otherwise, it recurs with half the exponent, and then checks if the exponent is odd, multiplying the result by x.