搜索
查看: 1026|回复: 4
打印 上一主题 下一主题

【一天一练】【2014.5.24】【母牛生小牛】

[复制链接]
跳转到指定楼层
楼主
发表于 2014-5-24 13:36:47 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
本帖最后由 李掌柜 于 2014-5-29 20:17 编辑

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

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

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

样例输入
2
4
5
0


样例输出
2
4
6


注:1 本题目来源http://www.clang.cc
        2 所有做题并贴代码的小伙伴都有机会获得1~5个啊哈币
游客,如果您要查看本帖隐藏内容请回复


推荐
发表于 2014-7-31 23:14:38 | 只看该作者
{:soso__14347937040236606360_4:}每年年初生一头,两年两头,不是三头牛吗...还有一头去哪了...
板凳
发表于 2015-9-28 21:42:53 | 只看该作者
学习一下
地板
发表于 2017-7-9 22:06:42 | 只看该作者
After 100 years,there are 1300 cows !!!

[mw_shl_code=c,true]#include <stdio.h>
#include <math.h>
void play(int );

int main(void)
{
    int n = 0;
    while(n <= 50)
    {
        play(n);
        ++ n;
    }
    return 0;
}

/*
    第0年 第1年 第2年 第3年 第4年 第5年 第6年 第7年 第8年 第9年 第10年
      A     A     A     A     A     A     A     A    ...    A     ...
            A1    A1    A1    A1    A1    A1    A1          A1
                  A2    A2    A2    A2    A2    A2          A2
                        A3    A3    A3    A3    A3          A3
                              A4    A4    A4    A4          A4
                                    A5    A5    A5          A5
                                    A1-1  A6    A6          A6
                                          A1-1  A7          A7
                                          A2-1  A1-1        A8
                                                A2-1        A9
                                                A3-1        A1-1
                                                            A2-1
                                                            A3-1
                                                            A4-1
                                                            A5-1
                                                            A1-1-1

years:  0   1   2   3   4   5   6   7   8   9   10  11  12  13  14  15  16  17
cows:   1   2   3   4   5   7   9   11  13  16  19  22  25  29  33  37  41  46
------------------------------------------------------------------------------
-:      1   1   1   1   1   2   3   4   5   7   9   11  13  16  19  22  25  29
*/

void play(int years)
{
    int cow = 1;
    int step = 4;   // 小牛每隔4年会产一头小牛
    int i,point;
    int x = 1;

    if(years % step == 0)
    {
        point = years / step;
        int d = point * (point - 1) + pow((point - 2),2);   //  通项公式
        int cha = (point - 1) * step;                       //  初始值
        cow = cow + cha + d + (step - 1) * point;
    }
    else
    {
        point = years / step + 1;
        int d = point * (point - 1) + pow((point - 2),2);
        int cha = (point - 1) * step;
        cow = cow + cha + d + ((years % step) - 1) * point;
    }
    printf("%d years -> %d cows\n",years,cow);
}
[/mw_shl_code]
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

广播台
特别关注
快速回复 返回顶部 返回列表