快速幂运算

/*
    快速幂运算 
*/
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
typedef long long LL;
LL binaryPow(LL a,LL b,LL m){
    if(b == 0) return 1;
    if(b%2 == 1) return a * binaryPow(a,b-1,m) % m;
    if(b%2 == 0){
        LL mul = binaryPow(a,b/2,m) % m;
        return mul * mul % m; 
    }
}
LL binaryPow2(LL a,LL b,LL m){
    LL ans = 1;
    if(b == 0) return 1;
    while(b){
        if(b&1){
            ans = ans * a % m;
        }
        a = a * a % m;
        b >>= 1;
    }
    return ans;
}
int main(void){
    cout << binaryPow(2,5,10) << endl;
    cout << binaryPow(2,5,10) << endl;
} 

注意:b % 2 == 0 时候不要直接返回 binaryPow(a,b/2,m) * binaryPow(a,b/2,m);
因为这样时间复杂度就会上升到O(b),而不是O(logb)

原文地址:https://www.cnblogs.com/zuimeiyujianni/p/8524714.html