题目给a和b,求a^b取模1000000007的结果;
直接用power没法求很大的数,也比较慢;
可以用二分幂的思想:
如果要求a^b 复杂度是O(b),那么可以先求出a^2,然后只要乘方b/2,复杂度就是O(b/2);
代码如下:
#include <cmath>
#include <iostream>
using namespace std;
typedef unsigned long long ll;
#define M 1000000007
ll po(ll a, ll b, ll M){
ll ans=1;
a=a%M;
while(b>0){
if(b%2) ans=ans*a%M;
a=a*a%M;
b/=2;
}
return ans;
}
int main() {
ll a,b;
cin>>a>>b;
cout<<po(a,b)<<endl;
return 0;
}
有一份更优雅的代码:
int po(int a,int b)
{
int ans = 1,base = a;
while(b!=0)
{
if(b&1)
ans *= base;
base *= base;
b>>=1;
}
return ans;
}
错点:
1.b&1用于判断b的最后一位是否是1,是1的话就是true则是奇数,否则是偶数;
2.取模的依据是如下公式: