/************** 快速幂模板 调用:Quk_Mul(a,b,mod) 返回:a^b%mod 复杂度:当mod>10^9,log(mod)*log(b),否则log(b) ***************/ long long Mod_Mul(long long a,long long b,long long mod) { long long msum=0; while(b) { if(b&1) msum = (msum+a)%mod; b>>=1; a = (a+a)%mod; } return msum; } long long Quk_Mul(long long a,long long b,long long mod) { bool qmflag=mod>1e9?1:0; long long qsum=1; while(b) { if(b&1) qsum = (qmflag==1) ? Mod_Mul(qsum,a,mod) : (qsum*a)%mod; b>>=1; a = (qmflag==1) ? Mod_Mul(a,a,mod) : (a*a)%mod; } return qsum; }
原文:http://www.cnblogs.com/chenhuan001/p/5060514.html