問題:
有一對兔子,從出生後第3個月起每個月都生一對兔子,小兔子長到第三個月後每個月又生一對兔子,假如兔子都不死,問每個月的兔子總數爲多少?
分析:
3月的數量=2月的數量+1月的數量
4月的數量=3月的數量+2月的數量
...........
代碼實現
public static void main(String[] args) {
int now_1 = 1;//當前-1
int now = 1;//當前
int nows;
int m = 5;//月份
if(m<=2){
System.out.println(now);
return;
}
for(int i=3;i<=m;i++ ){
nows = now;//此刻now變爲now_1,用nows記錄
now = now_1 + now;//f(n) = f(n-1)+f(n-2)
now_1 = nows; //重新賦值now_1
}
System.out.println(now);
for(int i = 1;i<=m;i++){
System.out.println(i+"月:"+fib(i));
}
}
/**
* 遞歸算法
* @param month
* @return
*/
public static int fib(int month){
if(month == 1 || month == 2){
return 1;
}else{
return fib(month-1)+fib(month-2);
}
}