ProgramAlgTrain/20240919/CSP常考算法模板/快速幂.cpp
2024-09-19 10:22:41 +08:00

27 lines
469 B
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <bits/stdc++.h>
using namespace std;
int b, p, k;
/*
原理a*b%k=(a%k)*(b%k)%k
对于任何一个自然数p=2*(p/2)+p%2
*/
int f(int p) {
if(p==0) // b^0%k
return 1%k;
int t=f(p/2)%k;
t=(t*t)%k; // b^p%k=(b^(p/2))^2%k
if(p%2==1)
t=(t*b)%k; // 如果p为奇数则b^p%k=((b^(p/2))^2)*b%k
return t;
}
int main(){
cin>>b>>p>>k;
int tmpb=b;
b%=k;
printf("%d^%d mod %d=%d", tmpb, p, k, f(p));
return 0;
}