题目描述:
实现函数double Power(double base,int exponent),求base的exponent次方。不得使用库函数,同时不需要考虑大数问题。
解决思路:
1.最简单的思路是从1到exponent进行循环,对base进行自乘;缺点:忽略了底数和指数取得特殊值的情况(底数为0或者指数为0,负数的情况)
代码如下:
public static double Power(double base,int exponent){ double result = 1.0; for (int i = 1;i<=exponent;i++){ result *= base; } return result; }
2.对思路1的缺点进行解决即可
代码如下:
public static double Power1(double base,int exponent){ double result = 0.0; //如果底数为0 if(base == 0) return 0.0; //如果指数为0 if(exponent == 0) return 1.0; //如果指数小于0 int ex = 0; if(exponent < 0) { ex = -exponent; return 1.0 / Power2(base, ex); } return Power2(base,exponent); }
3.对原始的函数进行优化(使用递归的方法):
当指数为偶数时;double Power(double base,int exponent) = double Power(double base,int exponent/2) * double Power(double base,int exponent/2);
当指数为奇数时;double Power(double base,int exponent) = double Power(double base,int (exponent-1)/2) * double Power(double base,int (exponent-1)/2) * base;
代码如下:
public static double Power2(double base,int exponent){ if(exponent == 0) return 1; if(exponent == 1) return base; double result = Power2(base,exponent >> 1); result *=result; if(exponent % 2 !=0) result *= base; return result; }