【C++】快速幂运算

迭代

可以将幂运算的幂改为二进制写法,很容易就能找到其中的规律。

class Solution {
public:
    int m = 1000000007; // 取模防止结果超出范围
    long myPow(long x, int n) {
        long res = 1;
        while (n > 0) {
            if (n & 1) res = res * x % m;
            x = x * x % m;
            n >>= 1; // 相当于n=n/2
        }
        return res;
    }
};

递归

快速幂的另一种理解方式为:

  • 当b为偶数时,a^b可以转为a^2的b/2次方。
  • 当b为奇数时,a^b可以转为a^2的b/2次方,再乘以a。
class Solution {
public:
    int m = 1000000007; // 取模防止结果超出范围
    long myPow(long x, int n) {
        if (n == 0) return 1;
        long res = myPow(x * x % m, n / 2);
        if (n & 1) res *= x;
        return res % m;
    }
};
posted @ 2021-02-25 10:20  tmpUser  阅读(305)  评论(0编辑  收藏  举报