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]
|