母牛的故事
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 63980 Accepted Submission(s): 31799
Problem Description
有一头母牛,它每年年初生一头小母牛。每头小母牛从第四个年头开始,每年年初也生一头小母牛。请编程实现在第n年的时候,共有多少头母牛?
Input
输入数据由多个测试实例组成,每个测试实例占一行,包括一个整数n(0<n<55),n的含义如题目中描述。
n=0表示输入数据的结束,不做处理。
n=0表示输入数据的结束,不做处理。
Output
对于每个测试实例,输出在第n年的时候母牛的数量。
每个输出占一行。
每个输出占一行。
Sample Input
2 4 5 0
Sample Output
2 4 6
Author
lcy
Source
Recommend
lcy | We have carefully selected several similar problems for you: 2041 2046 2044 2045 2050
1.非递归
#include<stdio.h>
int main(){
int n;
while(scanf("%d",&n) != EOF && n>0 && n<55){
int one,two,three,fourUp;
if(n<=4){
printf("%d\n",n);
}else{
n = n-4;
one = two = three = 1,fourUp = 1;
for(int i = 1;i <= n;i++){
fourUp = fourUp + three;
three = two;
two = one;
one = fourUp;
}
printf("%d\n",one + two + three + fourUp);
}
}
return 0;
}
2.递归
#include "stdio.h"
int fun(int x)
{
int c;
if(x<=3)
c=x;
if(x>3)
c=fun(x-1)+fun(x-3);
return c;
}
int main()
{
int n,sum;
while(scanf("%d",&n)!=EOF&&n!=0)
{
sum=fun(n);
printf("%d\n",sum);
}return 0;
}