【题目来源】
https://www.luogu.com.cn/problem/P1226
【算法分析】
快速幂就是快速计算底数a的n次幂,其时间复杂度为O(log₂n)。
与朴素幂运算的时间复杂度O(n)相比,快速幂的计算效率有了极大的提高。
矩阵快速幂的思想和快速幂的思想是一样的。无非就是底数变为矩阵了。所以,在计算矩阵快速幂时,只需在代码中定义一下矩阵的乘法即可。
利用位运算实现快速幂,原理如下:
即将十进制幂转换为二进制幂,然后利用二进制位间的倍增关系递推,达到快速计算幂的过程。
计算过程中,为了防止溢出,需要进行“取模”运算,其运算规则如下:
(a+b)%p=(a%p+b%p)%p
(a-b)%p=(a%p-b%p)%p
(a*b)%p=(a%p*b%p)%p
【算法代码】
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
int fastPow(LL a,LL n,LL p) {
LL ans=1;
while(n) {
if(n&1) ans=ans*a%p;
a=a*a%p;
n>>=1;
}
return ans;
}
int main() {
LL b,p,k;
cin>>b>>p>>k;
cout<<b<<"^"<<p<<" mod "<<k<<"="<<fastPow(b,p,k)%k;
return 0;
}
/*
in:2 10 9
out:2^10 mod 9=7
in:1 0 1
out:1^0 mod 1=0
*/
【参考文献】
https://www.luogu.com.cn/problem/solution/P1226
https://blog.csdn.net/qq_19782019/article/details/85621386