
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)
1#include <stdio.h>
2
3double myPow(double x, int n) {
4 long long N = n;
5 if (N < 0) {
6 x = 1 / x;
7 N = -N;
8 }
9 double result = 1;
10 while (N) {
11 if (N % 2 == 1) {
12 result *= x;
13 }
14 x *= x;
15 N /= 2;
16 }
17 return result;
18}
19
20int main() {
21 printf("%f\n", myPow(2.00000, 10));
22 printf("%f\n", myPow(2.10000, 3));
23 printf("%f\n", myPow(2.00000, -2));
24 return 0;
25}The C solution iteratively calculates the power using a loop. We adjust for negative exponents by taking the reciprocal of x and converting n to positive. This solution uses long long to handle large powers and iteratively squares the base, multiplying it to the result if the current power is odd.
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
1function
This JavaScript solution employs a helper function to recursively calculate the power. Using JavaScript's handling of floating-point numbers and Math.floor for division, it effectively splits the problem into recursive subparts.