一只羊的寿命是五年 他会在二岁和四岁 分别产下一只羊 如果一个牧场第一年引进一只羊 请问N年后 这个羊圈 有几只羊?(不考虑羊的交配以及疾病等因素)
先说下分析思路:
1)由题意得知:在N年内,所有羊仅在偶数年生育;羊的寿命为五年;
2)将羊圈看成一个大的容器,羊圈中最终的数量=羊的出生数量-羊的死亡数量。
以下先列出20年之内,每年羊的出生数量、羊的死亡数量:
偶数年 出生数量 死亡数量 增长数量
0 1 0 1
2 1 0 1
4 2 0 2
6 3 1 2
8 5 1 4
10 8 2 6
12 13 3 10
14 21 5 16
16 34 8 26
18 55 13 42
20 89 21 68
观察20年内羊的增长数量得知,从第6年开始,偶数年增长数量为斐波那契数列:2,4,6,10,16,26,42,68,....
所以,在N年内,羊的总数量=1+1+2+(从第6年至N年内每偶数年的增长数量斐波那契数列总和);
以上就是本思路,不多说了,直接上代码:
/**
* 获得N年后羊总数量
* @param year 多少年
* @return
*/
public static long getTotalCountByYear(int year){
if(year%2!=0) year--;
long _1thCount = 2;// 第6年增长数量
long _2thCount = 4;// 第8年增长数量
long _3rdCount = _2thCount+_1thCount;// 第10年增长数量
long totalCount = _1thCount+_2thCount+_3rdCount;
System.out.print(_1thCount+","+_2thCount+","+_3rdCount+",");
for(int i=12;i<=year;i=i+2){
_1thCount = _2thCount;
_2thCount = _3rdCount;
_3rdCount = _2thCount+_1thCount;
totalCount = totalCount + _3rdCount;
System.out.print(_3rdCount+",");
}
return 1+1+2+totalCount;
}
由以上方法得出100年之后羊圈羊的数量:40730022148,而且和之前的一些算法相比,在效率方面也很高。。。所以真正的性能优化,在很大程度上取决于算法,而算法优化,更是取决于所选的思路。
由此题看来,还真应了那句话,“给我一个女人,我就能创造出一个民族。。。“O(∩_∩)O哈哈~