母牛问题

来源:互联网 发布:向量化编程为何快 编辑:程序博客网 时间:2024/06/11 07:03

Description

有一头母牛,它每年年初生一头小母牛。每头小母牛从第四个年头开始,每年年初也生一头小母牛。请编程实现在第n年的时候,共有多少头母牛?

Input

输入数据由多个测试实例组成,每个测试实例占一行,包括一个整数n(0<n<55),n的含义如题目中描述。
n=0表示输入数据的结束,不做处理。

Output

对于每个测试实例,输出在第n年的时候母牛的数量。
每个输出占一行。

Sample Input

2

4

5

0

Sample Output

2

4

6

第一年有一头,第二年有一头,以此类推,我们可以手工得到一个列表:
其中母牛个体一列中m(n)表示岁数为n年的母牛有m头.由此列表我们可以看出f4 = f1 + f3 = 2; f5 = f2 + f4 = 3; f6 = f3 + f5 = 4; f7 = f4 + f6 = 6; f8 = f5 + f7 = 9;
因此我们可以归纳出:
这是斐波那契数列的变形,因此我们可以采用迭代方法来解决,也可以使用递归函数解决.

#include<cstdio>#include<cstdlib>int s[60];int main(){    int n;    while(scanf("%d" , &n) != EOF && n)    {        for(int i = 1; i <= n; i++)        {            if(i < 4)                s[4] = s[i] = i;            else            {                s[4] = s[1] + s[3];                s[1] = s[2];                s[2] = s[3];                s[3] = s[4];            }        }        printf("%d\n" , s[4]);    }    return 0;}


#include<cstdio>#include<cstdlib>int main(){    int n;    int s[60] = {1,1,2,3};    for(int i = 4 ; i < 55 ; i++)        s[i] = s[i-1] + s[i-3];    while(scanf("%d" , &n) != EOF && n)    {        printf("%d\n" , s[n]);    }    return 0;}


0 0
原创粉丝点击