今天练习时碰到斐波那契数列,循环和递归的代码分别统计了一下执行时间。递归还是相当慢的。
找了一篇介绍比较详细的博文,闲暇时可以再看看。 链接
package exrcise;
public class Demo1 {
public static void main(String[] args) {
/*
* 用循环实现不死神兔
故事得从西元1202年说起,话说有一位意大利青年,名叫斐波那契。
在他的一部著作中提出了一个有趣的问题:假设一对刚出生的小兔一个月后就能长成大兔,
再过一个月就能生下一对小兔,并且此后每个月都生一对小兔,一年内没有发生死亡,
问:一对刚出生的兔子,一年内繁殖成多少对兔子?
1 1 2 3 5 8 13 21
* */
long start = System.currentTimeMillis();
int month = 44;
fibonacci(month);
long end = System.currentTimeMillis();
System.out.println("--------------------------------------------");
long used = end - start;
System.out.println("当前程序耗时:" + used + "ms.");
System.out.println("--------------------------------------------");
long start1 = System.currentTimeMillis();
System.out.println(cFibonacci(44));
long end1 = System.currentTimeMillis();
long used1 = end1 - start1;
System.out.println("当前程序耗时:" + used1 + "ms.");
}
private static long cFibonacci(int month) {
if(month == 1 || month == 2) {
return 1;
}else {
return cFibonacci(month-1) + cFibonacci(month - 2);
}
}
private static void fibonacci(int month) {
long nextMonth = 1;
long thisMonth = 1;
long temp = 0;
for(int i=1; i<=month; i++) {
if(i <= 2) {
nextMonth = 1;
}else {
temp = nextMonth;
nextMonth = nextMonth + thisMonth;
thisMonth = temp;
}
System.out.println(nextMonth);
}
}
}
1
1
2
...
701408733
--------------------------------------------
当前程序耗时:4ms.
--------------------------------------------
701408733
当前程序耗时:2793ms.