一隻羊的壽命是五年 他會在二歲和四歲 分別產下一隻羊 若是一個牧場第一年引進一隻羊 請問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哈哈~