题解 | #统计每个月兔子的总数#
统计每个月兔子的总数
http://www.nowcoder.com/practice/1221ec77125d4370833fd3ad5ba72395
/*1 1 2 3 5 8 13 21 34
典型递归
递归方程式:
x=1:
x=2:1
x>2:f(x)=f(x-1)+f(x-2)
*/
#include <stdio.h>
int fun(int n){
if(n == 0) return 0;
else if(n == 1) return 1;
else return fun(n-1)+fun(n-2);
}
int main(){
int n;
while(scanf("%d",&n) != EOF){
printf("%d\n",fun(n));
}
}
//1 1 2 3 5 8 13 21 34
#include <stdio.h>
int main(){
int n1,n2,n3;//三种状态的兔子
int n; //月份
while(scanf("%d",&n) != EOF){
n1 = 0;
n2 = 0;
n3 = 1;
for(int i = 3; i <= n; i++){
int tmp = n3;
n3 += n2; //成熟兔子
n2 = n1; //两个月大的兔子
n1 = n3; //新生兔子
}
printf("%d\n",n1 + n2 + n3);
}
}