有如下公式:
因此我们求解a^n时,可以先求解r=a^(n/2)
比如求解r=3^5,先求解3^(5-1)/2=3^2=9,因此3^5=9×9×3=243
注:我们需判断a是否为零,n的正负情况
代码:
/** * Created by wuchao on 17-3-29. */ import java.util.*; public class test { public static int array[] = {1,1,0,1,1,1,1}; public static void main(String[] args) { System.out.println(power(2,-3)); } public static double power(double base,int exponent){ //首先判断base是否为0,但double不能直接和0比较 if(base<0.0000001 && base>-0.0000001) return 0; if(exponent==0) return 1; int flag=1;//正负标志 if(exponent<0) { flag=-1; exponent=-exponent; } double result = powerWithunsigned(base,exponent); if(flag>0) return result; return 1/result; } //exponent>0 public static double powerWithunsigned(double base,int exponent){ if(exponent==0) return 1; if(exponent==1) return base; double result = powerWithunsigned(base,exponent>>1); result = result*result; //如果exponent为奇数 if((exponent&1)>0){ result=result*base; } return result; } }
时间: 2024-12-27 13:40:48