快速幂运算模板:
(1)快速幂运算是指在给定模数mod的情况下,在系统有限的时间计算大数的指数次方的值,如计算123^3445 mod 163的值,甚至可以直接手算.
- 时间复杂度:O(log(n));
- 非递归调用;
- 1&n判断n数字是否为奇数或者偶数;
- 计算x^n mod mod,范围long long数据类型.
typedef long long ll;
ll mod_pow(ll x,ll n,ll mod){
ll res=1;
while(n>0){
if(1&n) res=res*x%mod;
x=x*x%mod;
n=n/2;
}
return res;
}
完整代码示例:
#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
/**采用非递归调用,在O(logn)时间复杂度下求解**/
/**计算123^3445%163**/
void pow_(int x,int n,int mod){
int ans=1,k=1,kk=1;
while(n>0){
if(n&1) {
ans=ans*x%mod;
printf("#第%d次更新答案的值: ans=%d\n",k++,ans);
}
x=x*x%mod;
n=n/2;
printf("#第%d次while循环后x,n,mod的值:x=%d n=%d mod=%d\n\n",kk++,x,n,mod);
}
printf("最后的答案####ans:%d\n",ans);
}
int main(){
pow_(123,3445,163);
return 0;
}
详细运行结果:
(2)时间复杂度:
- O(log(n));
- 递归调用;
typedef long long ll;
ll mod_pow(ll x,ll n,ll mod){
if(n==1) return 1;
ll res=mod_pow(x*x%mod,n/2,mod);
if(n&1) res=res*x%mod;
return res;
}
(3)快速乘运算:快速乘运算是计算a*b % mod,如计算12347372*73838473%10234,大数相乘可能会溢出,并且精度可能缺失.
LL mul_mod(LL a,LL b,LL mod){
LL ret=0;
while(b){
if(b&1) ret=ret+a;
if(ret>=mod) ret-=mod;
a=a+a;
if(a>=mod) a-=mod;
b>>=1;
}
return ret;
}
(4)快速乘运算+快速幂运算:提升计算x^n mod mod的速度.
LL mul_mod(LL a,LL b,LL mod){
LL ret=0;
while(b){
if(b&1) ret=ret+a;
if(ret>=mod) ret-=mod;
a=a+a;
if(a>=mod) a-=mod;
b>>=1;
}
return ret;
}
LL pow_mod(LL a,LL b,LL mod){
LL ret=1;
while(b){
if(b&1)ret=mul_mod(ret,a,mod);
a=mul_mod(a,a,mod);
b>>=1;
}
return ret;
}