leetcode 372

题意:求 a^b mod 1337的值。

两个重要公式:1)(a*b)%k = (a%k) * (b%k)%k

2) a^b % k = (a%k)^b %k

分治法,拆成两个子问题求解。

class Solution {
public:
    int superPow(int a, vector<int>& b) {
        long res = 1;
        for(int i=0; i<b.size();i++){
            res = pow(res,10)*pow(a,b[i])%1337;
        }
        return res;
    }
    int pow(int x, int n){
        if(n==0) return 1;
        if(n==1) return x%1337;
        return pow(x%1337, n/2) * pow(x%1337, n-n/2)%1337;
    }
};
原文地址:https://www.cnblogs.com/Bella2017/p/10913808.html