为什么要用快速乘/快速幂
快速幂
传统的求幂算法时间复杂度非常高(为O(指数n)),因为当指数n非常大的时候,需要执行的循环操作次数也非常大,而快速幂能帮我们以相对更少的时间算出指数非常大的幂。
快速乘
加法比乘法快。可以用较多的加法来取代乘法来减少时间复杂度(乘法分配律?)
原理
见:https://blog.csdn.net/maxichu/article/details/45459715
(绝不承认自己懒)
模板
#include<stdio.h>
#define LL long long
LL mul_mod(LL a,LL b,LL c) //a*b mod c快速乘
{
LL ans=0;
while(b)
{
if(b%2)
ans=(ans+a)%c;
a=(a+a)%c;
b/=2;
}
return ans;
}
LL pow_mod(LL a,LL b,LL c) //a^b mod c快速幂
{
LL res=1;
a=a%c;
while(b)
{
if(b%2)
res=(res*a)%c; //res=mul_mod(res,a,c);更快
a=(a*a)%c; //a=mul_mod(a,a,c);更快
b/=2;
}
return res;
}
int main()
{
LL a,b,c;
scanf("%lld%lld%lld",&a,&b,&c);
printf("%lld\n",mul_mod(a,b,c));
printf("%lld\n",pow_mod(a,b,c));
return 0;
}
例题
HDU 2035
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
#include<algorithm>
#include<iostream>
#define LL long long
#define INF 0x3f3f3f3f
const int MAX=1e6+50;
using namespace std;
LL pow_mod(LL a,LL b,LL c)
{
LL res=1;
a=a%c;
while(b)
{
if(b%2)
res=(res*a)%c; //res=mul_mod(res,a,c);
a=(a*a)%c; //a=mul_mod(a,a,c);
b/=2;
}
return res;
}
int main()
{
LL a,b;
while(~scanf("%lld%lld",&a,&b)&&a!=0&&b!=0)
printf("%lld\n",pow_mod(a,b,1000));
return 0;
}
HDU 5187
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
#include<algorithm>
#include<iostream>
#define LL long long
#define INF 0x3f3f3f3f
const int MAX=1e5+50;
using namespace std;
LL mul_mod(LL a,LL b,LL c) //a*b mod c
{
LL ans=0;
while(b)
{
if(b%2)
ans=(ans+a)%c;
a=(a+a)%c;
b/=2;
}
return ans;
}
LL pow_mod(LL a,LL b,LL c) //a^b mod c
{
LL res=1;
a=a%c;
while(b)
{
if(b%2)
res=mul_mod(res,a,c);
a=mul_mod(a,a,c);
b/=2;
}
return res;
}
int main()
{
long long a,b;
while(~scanf("%lld%lld",&a,&b))
{
if(a==1) //此处需对1特判
{
if(b==1)
printf("0\n");
else
printf("1\n");
continue;
}
printf("%lld\n",(pow_mod(2,a,b)-2+b)%b);
}
return 0;
}
注意到模板中快速幂函数的这两行
if(b%2)
res=(res*a)%c; //res=mul_mod(res,a,c);
a=(a*a)%c; //a=mul_mod(a,a,c);
例题二的代码中用的注释中的格式,在快速乘的基础上执行快速幂,更快,有的题不需要(如题一),而有的题则必须这样用(如题二,不调快速乘A不了),建议直接按注释格式打板子吧,谁嫌快呢