常规求幂,二分求幂,快速幂(位运算)
分为三种情况:b=0 b>0 b<0
1)常规求幂 :
//常规
double power1(double a,int b){//注意b是int型
if (b==0) return 1;
double s=1;
if (b > 0){
while (b--){
s*=a;
}
return s;
}
if (b<0){
int c=-b;
while (c--)
s*=a;
return 1/s;
}
}
2 ) 二分求幂:
组合:a*a*a*a*a*a=(a*a)*(a*a)*(a*a),这样就将6次乘法变成了3次乘法运算。减少重复计算的次数。
//二分
double power2(double a,int b){
if (b == 0) return 1;
if (b > 0){
double s=1;
double res=a;
while (b != 0){
if (b % 2)
s*=res;
res*=res;
b/=2;
}
return s;
}
if (b<0){
double s=1,res=a;
int c=-b;
while (c!= 0){
if (c%2==1)
s*=res;
res*=res;
c/=2;
}
return 1/s;
}
}
3 ) 快速幂(位运算)
b可以看成是一个二进制,每一个1都可以看成是2的倍数。
a^21=(a^16)*(a^4)*(a^1)。
而21的二进制表示为10101。21 = 2^0+2^2+2^4
每次将b的二进制从右到左与1进行&运算。
//快速幂,位运算
double power3(double a,int b){
if (b == 0) return 1;
if (b>0){
double s=1,res=a;
while (b){
if (b&1)
s*=res;
b>>=1;
res*=res;
}
return s;
}
if (b < 0){
double s=1,res=a;
int c = -b;
while (c){
if (c & 1)
s*=res;
c>>=1;
res*=res;
}
return 1/s;
}
}