快速幂学习

求出a^k%p的结果,时间复杂度是O(logk)

把k拆成2的次方和。最多是logk个

a^2^0%p

a^2^1%p

a^2^2%p

…………

a^2^logk%p

预处理:

#include
using namespace std;
typedef long long LL;
int qmi(int a, int k, int p){
    int res = 1;
    while(k){
        if(k & 1)res = (LL)res * a % p;
        k >>= 1;
        a = (LL)a * a % p;
    }
    return res;
}
int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n; cin >> n;
    while(n--){
        int a, k, p;
        cin >> a >> k >> p;
        cout << qmi(a, k, p) << endl;
    }
    
    return 0;
}

你可能感兴趣的:(学习)