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) //if n是偶数
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) //等价n%2!=0
result *= x;
n >>= 1; // 等价n/2
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");//pow:230ms
time1 = System.currentTimeMillis();
for (int i = 0; i < 10000000; i++) {
notRecursivePow(6, 1000);
}
time2 = System.currentTimeMillis();
System.out.println("notRecursivePow:"+(time2-time1)+"ms");//notRecursivePow:126ms
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");//Math.pow:4ms 几乎固定在4ms左右
}
}
Weiss数据结构与算法--练习2.23(幂运算)
最新推荐文章于 2021-01-12 18:34:38 发布