兔子繁殖问题:
有一只兔子,从出生后第3个月起每个月都生一只兔子,小兔子长到第三个月后每个月又生一只兔子,假如兔子都不死,问每个月的兔子总数为多少?
1.问题分析:
我们可以根据题目分析,得出如上图。兔子的对数从第一个月份开始分别是 1,1,2,3,5,8我们可以的得出这样关系
f(1) = 1
f(2) = 1
f(n) = f(n - 1) + f(n - 2)
1.采用第一种方法代码如下:
public class Rabbits {
public static void main(String[] args){
long a = System.currentTimeMillis();
for(int i = 1; i <= 40; i++) {
System.out.println(i + “:” + rabbits(i));
}
long b = System.currentTimeMillis();
long c = b-a;
System.out.println©;
}
public static long rabbits(int x) {
if(x == 1 || x == 2) {
return 1;
}else {
return rabbits(x - 1) + rabbits(x - 2);
}
}
}
编程中我们可以发现,递归虽然看起来程序清晰,当给更多的月份
或者给的数更大,速度就会很明显变慢,当为40的时候,耗费时间长达880毫秒。
2.采用第二种方法代码如下:
public class Rabbit {
static long now = 0l;
static long last2 = 1l;
static long last1 = 0l;
static long temp = 0l;
public static void main(String[] args) {
long a = System.currentTimeMillis();
for(int i = 1; i <= 40; i++) {
System.out.println( “第” + i + “月:” + rabbitnow(i));
}
long b = System.currentTimeMillis();
long c = b-a;
System.out.println©;
}
public static long rabbitnow(int x) {
now = last2 + last1;
temp = last1;
last1 = last2 + last1;
last2 = temp;
return now;
}
}
看起来逻辑较为复杂,但是耗费时间很少,只需5毫秒,在大量数据的情况下,最好使用第二种方法