数值的整数次方
给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。
思路:an=an/2*an/2(n为偶数)
= a(n-1)/2*a(n-1)/2*a(n为奇数)
根据这个公式,我们可以把这个当成一个递推公式,如an与a(n/2)的关系(an/2与a(n-1)/2)相等。
public class multi{ public double getMulti(double base,int exponent){ if(exponent == 0) return 1; if(exponent == 1) return base; boolean flag = false; if(exponent<0) { flag = true; exponent = Math.abs(exponent); } double result = 0.0; result = getMulti(base,exponent>>1); result *= result; if((exponent&1)==1){ result *= base; } if(flag){ result = 1/result; } return result; } public static void main(String[] args){ multi m = new multi(); double result = m.getMulti(10,-1); System.out.println(result); } }
public double Power(double base, int exponent) { if(exponent == 0) return 1; if(exponent == 1) return base; boolean flag = false; if(exponent<0){ flag = true; } double result = 0.0; exponent = Math.abs(exponent); result = Power(base,exponent/2); if((exponent & 1)==0){ result *= result; }else{ result = result*result*base; } if(flag) result = 1/result; return result; }