每天一道算法--经典兔子繁殖迭代问题(斐波那契数列)

时间:2021-02-13 16:23:52

题目:古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?
1.程序分析: 兔子的规律为数列1,1,2,3,5,8,13,21….
由规律可知:
f(x) = f(x-1)+f(x-2)
符合斐波那契数列(斐波那契数列系数就由之前的两数相加)

public class Rabbit {

private static long rabbit(int month){
long rabbitOne = 1L;
long rabbitTwo = 1L;
long rabbit;
for(int i=3;i<=month;i++){
rabbit = rabbitTwo;
rabbitTwo = rabbitOne + rabbitTwo;
rabbitOne = rabbit;
}
return rabbitTwo;
}

public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int i = in.nextInt();
System.out.println(i+"个月后兔子总数:"+rabbit(i));
main(args);
}

}