快 速 幂~~~
栗子:若求211,因11过大,On大,则将211转换为2(23)2(20)2(21)
快速幂代码~~
下为a^b % n代码;
//非递归代码
int quickpow(int a,int b,int n){
int q = 1;
while(b){
if(b % 2 == 1)q = q * a;
a = a * a % n;
b = b / 2;
}
return q;
}
//递归代码
int quickpow(int a,int b,int n){
if(b == 1)return a;
if(b % 2 == 0){
int t = quickpow(a,b / 2,n);
return t * t % n;
}else{
int t = quickpow(a,b / 2,n);
t = t * t % n;
t = t * a % n;
return t;
}
}
浙公网安备 33010602011771号