幂的计算
Description
给定一个实数a和一个整数b,编写一个函数来计算a的b次幂;
Input
输入a和b,中间用英文逗号隔开
-100.0<a<100.0
-2^31 <=b<= 2^31-1
要么a不为零,要么b>0
-10000≤a^b≤10000
Output
a的b次幂的值
输出值请确保保留六位小数,且输出结果末尾不带有回车!!!
Sample
代码
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String s[] = reader.readLine().split(",");
double a = Double.valueOf(s[0]);
long b = Integer.valueOf(s[1]);
System.out.printf("%.6f",pow(a,b));
}
public static double pow(double a,long b){
if(a==0){
return 0;
} else if (b==0) {
return 1.0;
} else if(b==1){
return a;
} else if (b==-1) {
return 1.0/a;
} else if (b%2==0&&(b!=0)) {
double temp = pow(a,b/2);
return temp*temp;
} else if (b%2==1&&(b!=1)) {
return a*pow(a,b-1);
} else if (b%2==-1&&(b!=-1)) {
return a*pow(a,b-1);
}
return a;
}
}
思路
使用了分治法,不断缩小b范围,减小计算次数,即快速幂。
a的正数次幂即为相乘,负数次幂可以看为1.0/a