package com.haowu.testHashEquels;
public class BrokerTest {
public static void main(String[] args) {
long start = System.currentTimeMillis();
//采用递归方法求值
getsum(50);
long end = System.currentTimeMillis();
System.out.println(end - start);
long start2 = System.currentTimeMillis();
//采用简单的for循环
getsumab(50);
long end2 = System.currentTimeMillis();
System.out.println(end2 - start2);
}
public static void getsum (int n){
float sum = 0;
for (int i = 1; i <= n; i++) {
float a = geta(i);
float b = getb(i);
sum+=(a/b);
}
System.out.println(sum);
}
/**递归方式求分子*/
public static float geta(int n){
if(n==1){
return 2;
}
if(n==2){
return 3;
}
return geta(n-2) +geta(n-1);
}
/**递归方式求分母*/
public static float getb(int n){
if(n==1){
return 1;
}
if(n==2){
return 2;
}
return getb(n-2) +getb(n-1);
}
/**直接循环方式求值*/
public static void getsumab(int n){
float a = 1;
float b = 2;
float sum = 0;
for (int i = 1; i <= n ; i++) {
sum += (b/a);
float t = a;
a=b;
b=a+t;
}
System.out.println(sum);
}
}
当求前50项的和时分别耗时如下:
递归方式求前50项之和为:81.201294
递归方式求前50项耗时为:187884ms
采用普通循环方式求前50项之和为:81.201294
采用普通循环方式求前50项耗时为:0ms