package cn.yjnull.datastrhomework;
/** * 幂运算 * @author Yjnull * */
public class DataStr2_23_Pow {
public static double pow(double x,int n){
if(0==n) return 1;
if(1==n) return x;
if(n%2==0)
return pow(x*x,n/2);
else
return pow(x*x,n/2)*x;
}
public static double notRecursivePow(double x,int n){
double result = 1;
/** * 例:x=3,n=9 * 1. n&1!=0 result=3 --> n=4 --> x = 3*3=3^2 * 2. n&1==0 --> n=2 --> x = 3^2 * 3^2=3^4 * 3. n&1==0 --> n=1 --> x = 3^8 * 4. n&1!=0 result=3*3^8=3^9 --> n=0 --> x=3^16 * 5. return 3^9; */
while(n>0){
if((n&1)!=0)
result *= x;
n >>= 1;
x *= x;
}
return result;
}
public static void main(String[] args) {
long time1,time2;
time1 = System.currentTimeMillis();
for (int i = 0; i < 10000000; i++) {
pow(6, 1000);
}
time2 = System.currentTimeMillis();
System.out.println("pow:"+(time2-time1)+"ms");
time1 = System.currentTimeMillis();
for (int i = 0; i < 10000000; i++) {
notRecursivePow(6, 1000);
}
time2 = System.currentTimeMillis();
System.out.println("notRecursivePow:"+(time2-time1)+"ms");
time1 = System.currentTimeMillis();
for (int i = 0; i < 10000000; i++) {
Math.pow(6, 1000);
}
time2 = System.currentTimeMillis();
System.out.println("Math.pow:"+(time2-time1)+"ms");
}
}