一只羊的寿命是五年 他会在二岁和四岁 分别产下一只羊 若是一个牧场第一年引进一只羊 请问N年后 这个羊圈 有几只羊?(不考虑羊的交配以及疾病等因素)算法
先说下分析思路:性能优化
1)由题意得知:在N年内,全部羊仅在偶数年生育;羊的寿命为五年;ide
2)将羊圈当作一个大的容器,羊圈中最终的数量=羊的出生数量-羊的死亡数量。性能
如下先列出20年以内,每一年羊的出生数量、羊的死亡数量:优化
偶数年 出生数量 死亡数量 增加数量get
0 1 0 1it
2 1 0 1 class
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 totalCount;
}
由以上方法得出100年以后羊圈羊的数量:40730022144,并且和以前的一些算法相比,在效率方面也很高。。。因此真正的性能优化,在很大程度上取决于算法,
而算法优化,更是取决于所选的思路。
还真应了那句话,“给我一个女人,我就能创造出一个民族。。。“O(∩_∩)O哈哈~