题解:P1226 【模板】快速幂
jubaoyi2011 · · 题解
提供两种思路
第一种很好理解,由乘方的基本性质:
当
当
这在 c++ 中递归即可实现:
#include <bits/stdc++.h>
using namespace std;
int a, b, p;
int ksm(int x, int y){
if(y==0)return 1%p;
int t=ksm(x,y/2);
if(y%2==0)return 1ll*t*t%p;
else return 1ll*x*t%p*1ll*t%p;
}
int main(){
cin>>a>>b>>p;
printf("%d^%d mod %d=%d",a,b,p,ksm(a,b));
return 0;
}
我们还可以用倍增的方法解决此题:
基于任意整数都可以转换成若干个
这样一来,计算
由于
每移位一次,指数的二进制位置所表示的值都是之前的2倍,要累乘的值
下面模拟一下过程:
设结果
第一次:判断
第二次:判断
第三次:判断
第四次:判断
代码:
#include<bits/stdc++.h>
using namespace std;
int a, b, p;
int ksm(int x,int y){
int res=1;
while(y){
if(y&1)res=1ll*res*x%p;
y=y>>1;
x=1ll*x*x%p;
}
return res;
}
int main(){
cin>>a>>b>>p;
printf("%d^%d mod %d=%d",a,b,p,ksm(a, b));
return 0;
}