有一个叫做光速幂的算法可以(n为指数范围)预处理,然后求幂,通常用来应付同一底数,多次求幂的场景。由于 ,所以在这里是适用的。
思路是预处理
这样对于任意一个我们都可以通过上面两个数列中各取一项来求得
#include<cstdio>
const int BL=50000;//block's length的缩写,别想多了
typedef long long ll;
ll read(){
ll a=0;int op=1;char ch=getchar();
while(ch<'0'||'9'<ch){if(ch=='-')op=-1;ch=getchar();}
while('0'<=ch&&ch<='9'){a=(a<<3)+(a<<1)+(48^ch);ch=getchar();}
return a*op;
}
ll pow[BL+1];
ll powb[BL+1];
ll a,n;
ll P;
void ini(){
pow[0]=powb[0]=1;
for(int i=1;i<=BL;i++){
pow[i]=pow[i-1]*a%P;
}
for(int i=1;i<=BL;i++){
powb[i]=powb[i-1]*pow[BL]%P;
}
}
int main(){
a=read();
n=read();
P=read();
ini();
printf("%lld^%lld mod %lld=%lld",a,n,P,powb[n/BL]*pow[n%BL]%P);
return 0;
}