斐波那契数列又称黄金分割数列,还有一个俗称是兔子数列。指的是这样一个数列:0、1、1、2、3、5、8、13、21、34...
题目:斐波那契数列是一组第一位F1
和第二位F2
为1,从第三位开始,后一位是前两位和的一组递增数列Fn
=Fn-1
+Fn-2
。
那么当n
比较大时,Fn
也非常大,现在我们想知道,第n
项,Fn
等于多少
public class Test4 {
/**
* 第n位数字Fn=Fn-1+Fn-2之和,输入一个整数数字,该整数位数字总和是:
* 0、1、1、2、3、5、8、13、21、34
*/
// 根据上面数列分析,可以采用递归方式进行处理
private static Integer fiboPlus(Integer number) {
// 当输入数字为0或者1时直接返回当前值
if (number == 1 || number == 0) {
return number;
}
return fiboPlus(number - 1) + fiboPlus(number - 2);
}
public static void main(String[] args) {
long begin = System.currentTimeMillis();
System.out.println(fiboPlus(38 ));
long end = System.currentTimeMillis();
System.out.println("耗时:" + (end - begin) / 1000.00 + "s");
}
}
是不是发现当输入数字越大,所花时间越来越多,当数字大到一定程度,程序就会报内存溢出。所以要寻找更加性能更优的方法进行Fn求和。
public class Test4 {
/**
* 第n位数字Fn=Fn-1+Fn-2之和,输入一个整数数字,该整数位数字总和是:
* 0、1、1、2、3、5、8、13、21、34
*/
// 根据上面数列分析,可以采用递归方式进行处理
private static Integer fiboPlus(Integer number) {
// 当输入数字为0或者1时直接返回当前值
if (number == 1 || number == 0) {
return number;
}
return fiboPlus(number - 1) + fiboPlus(number - 2);
}
private static Integer fiboPlus2(Integer number) {
// 当输入数字为0或者1时直接返回当前值
if (number == 1 || number == 0) {
return number;
}
Integer first = 0;
Integer second = 1;
Integer temp = null;
for (int i = 1; i < number; i++) {
temp = first + second;
first = second;
second = temp;
}
return temp;
}
public static void main(String[] args) {
long begin1 = System.currentTimeMillis();
System.out.println(fiboPlus(45));
long end1 = System.currentTimeMillis();
System.out.println("耗时"+(end1-begin1)/1000.00+"s");
long begin2 = System.currentTimeMillis();
System.out.println(fiboPlus2(45));
long end2 = System.currentTimeMillis();
System.out.println("耗时"+(end2-begin2)/1000.00+"s");
}
}