当前位置:网站首页>50. Pow(x, n). O(logN)​ Sol

50. Pow(x, n). O(logN)​ Sol

2022-07-05 22:17:00 isee_ nh

Move the dichotomy of the official solution , The time complexity is O(logN)

Implement pow(x, n), which calculates x raised to the power n (i.e., xn).

​​​​class Solution {
public:
    double fastPow(double x, long long n) {
        if (n == 0) {
            return 1.0;
        }
        double half = fastPow(x, n / 2);
        if (n % 2 == 0) {
            return half * half;
        } else {
            return half * half * x;
        }
    }
    double myPow(double x, int n) {
        long long N = n;
        if (N < 0) {
            x = 1 / x;
            N = -N;
        }
        return fastPow(x, N);
    }
};

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: 2-2 = 1/22 = 1/4 = 0.25

Constraints:

  • -100.0 < x < 100.0
  • -231 <= n <= 231-1
  • -104 <= xn <= 104

Approach 2: Fast Power Algorithm Recursive

Intuition

Assuming we have got the result of x^n, how can we get x^{2n} ? Obviously we do not need to multiply x for another n times. Using the formula (x^n)^2=x^{2n}, we can get x^{2n} at the cost of only one computation. Using this optimization, we can reduce the time complexity of our algorithm.

Algorithm

Assume we have got the result of x^{n/2}, and now we want to get the result of x^n. Let A be result of x^{n/2}, we can talk about x^n based on the parity of n respectively. If n is even, we can use the formula (x^n)^2=x^{2n} to get x^n = A*A. If n is odd, then A*A=x^{n-1}. Intuitively, We need to multiply another xx to the result, so x^n = A*A*x. This approach can be easily implemented using recursion. We call this method "Fast Power", because we only need at most O(log⁡n) computations to get x^n.

原网站

版权声明
本文为[isee_ nh]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202140438525169.html