
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)
1using System;
2
3public class Solution {
4 public double MyPow(double x, int n) {
5 long N = n;
6 if (N < 0) {
7 x = 1 / x;
8 N = -N;
9 }
10 double result = 1;
11 while (N != 0) {
12 if ((N & 1) == 1) {
13 result *= x;
14 }
15 x *= x;
16 N >>= 1;
17 }
18 return result;
19 }
20
21 public static void Main() {
22 Solution sol = new Solution();
23 Console.WriteLine(sol.MyPow(2.00000, 10));
24 Console.WriteLine(sol.MyPow(2.10000, 3));
25 Console.WriteLine(sol.MyPow(2.00000, -2));
26 }
27}This C# solution employs bitwise operations, such as & and >>, to enhance performance during power computation. It handles negative values similarly by converting the power to positive and adjusting the base.
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.