题解 P1226 【【模板】快速幂||取余运算】

· · 题解

有一个叫做光速幂的算法可以O(\sqrt{n})(n为指数范围)预处理,然后O(1)求幂,通常用来应付同一底数,多次求幂的场景。由于

思路是预处理 $a^0,a^1,a^2,...,a^{\sqrt{n}} a^0,a^{\sqrt{n}},a^{2\sqrt{n}},...,a^n

这样对于任意一个k我们都可以通过上面两个数列中各取一项来求得a^k=a^{[\frac{k}{\sqrt{n}}] * \sqrt{n} } * a^{ k \% \sqrt{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;
}