快速幂

对于n的规模,我们到达到logn,可以用分治的思想

经过logb次b就变为1

递归实现:

int quickpow(int a,int b,int c){
    if(b==1) return a;
    int t=quickpow(a,b>>1,c);
    if(b%2==0)    return t*t%c;
    else{
    t=t*t%c;
    return t*a%c;
  }
}

循环实现:

int quickpow(int a,int b,int c){
    int t=1;
    while(b){
        if(b%2==1) t=t*a%c;
        a=a*a%c;
        b=b/2;
    }
    return t;
}
原文地址:https://www.cnblogs.com/yfr2zaz/p/10433348.html