Quick fast multiplication optimize power +

When a power of n in a time too, can use this optimized way, since the computer of multiplication time, the addition is calculated as the manner by splitting;

So there will be some that can accelerate the speed of code, specifically how did not get to the bottom, you remember him.

#include<cstdio>
#include<algorithm>
#include<math.h>
#include<string.h>
using namespace std;
typedef long long ll;
const int mod=1e9+7;
ll quick_mul(ll a,ll b,ll r)
{
ll ans=0;
while(b){
if(b&1) ans=(ans+a)%r;
a=(a+a)%r;
b>>=1;
}
return ans;
}
ll quick_pow(ll a,ll b,ll r)
{
ll ans=1;
while(b){
if(b&1) ans=quick_mul(ans,a,r);
a=quick_mul(a,a,r);
b>>=1;
}
return ans;
}
int main()
{
ll a,b;
while(scanf("%lld%lld",&a,&b)!=EOF){
ll ans=quick_pow(a,b,mod);
printf("%lld\n",ans);
}
return 0;
}

Guess you like

Origin www.cnblogs.com/pangbi/p/11488644.html