<span style="color: rgb(51, 51, 51); font-family: arial, 宋体, sans-serif; font-size: 14px; line-height: 24px; text-indent: 28px;">快速幂其时间复杂度为 O(log₂N), 比O(N)提高了很高效率</span>
例如求a的b次幂
则只需要从低位到高位取b的二进制位,是1就乘以a^(2^i-1)
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <algorithm>
using namespace std;
typedef pair<int, int> P;
typedef long long LL;
#define LOCAL
#define INF 0x3f3f3f3f
#define MAX_N
const int ret = 1e9 + 7;
LL quick_mod(LL a, LL b)
{
LL ans = 1;
//对可操作位进行操作
while(b)
{
if(b&1)
ans = ans*a;
b >>= 1;
a = a*a;//2^n
}
return ans;
}
int main()
{
#ifdef LOCAL
freopen("b:\\data.in.txt", "r", stdin);
#endif
//快速幂运算
cout <<quick_mod(2, 2)<<endl;
return 0;
}