普通幂取模

时间复杂度O(n)

代码:

ll general_pow(ll x,ll n,ll mod)
{
    ll res=1;
    for(int i=0;i<=n;i++)
        res=res*x%mod;
    return res;
}

 

快速幂取模x^n=(x*x)^(n/2)

时间复杂度O(lg(n)),远快于朴素算法

代码:

ll fast_pow(ll x,ll n,ll mod)
{
    ll res=1;
    while(n){
        if(n&1)res=res*x%mod;
        x=x*x%mod;
        n>>=1;
    }
    return res;
}

 

posted on 2020-04-12 16:04  新望  阅读(175)  评论(0)    收藏  举报