L J Z
0 1

快速幂

快速幂模板


LL mod_pow(LL x,LL n,LL mod)
{
        LL res = 1;
        while (n > 0) 
        {
            if (n&1)
            {
                //res = mod_mulit(res,x,mod);
                res = res*x%mod;
            }
            //x = mod_multi(x,x,mod);
            x = x*x%mod;
            n >>= 1;
        }
        return res;
}

而有时候,数据非常大,也会使快速幂爆掉的话,我们常常加上快速乘来优化时间:


/*只要将上述代码转换成注释掉的语句就可以
下面是快速乘的模板*/

LL mod_pow(LL x,LL n,LL mod)
{
        LL res = 1;
        while (n > 0) 
        {
            if (n&1)
            {
                res = mod_mulit(res,x,mod);
                // res = res*x%mod;
            }
            x = mod_multi(x,x,mod);
            //x = x*x%mod;
            n >>= 1;
        }
        return res;
}



posted @ 2016-07-24 18:23  小小钊  阅读(120)  评论(0编辑  收藏  举报