理论很简单,代码来自挑战程序设计竞赛.
非递归形式代码:
ll QPower(ll x,ll n,ll mod)
{
ll res=1;
while(n>0)
{
if(n&1)
res=res*x%mod;
x=x*x%mod;
n>>=1;
}
return res;
}
其中返回的值是(x^n)%mod
递归形式代码:
ll QPower(ll x,ll n,ll mod)
{
if(n==0)
return 1;
ll res=QPower(x*x%mod,n/2,mod);
if(n&1)
res=res*x%mod;
return res;
}