有一母牛,到4岁可生育,每年一头,所生均是一样的母牛,到15岁绝育,不再能生,20岁死亡,问n年后有多少头牛。
function cows ($n) {
$cows = [1];
for ($i = 1; $i <= $n; $i++) {
// 新出生的牛
$new_number = 0;
foreach ($cows as $age => $num) {
// 4岁到14岁的牛生育新的母牛
if ($age >= 3 && $age <= 13) {
$new_number += $num;
}
}
// 将新出生的牛加到数组开头
array_unshift($cows, $new_number);
// 取出数组的前20个单元
$cows = array_slice($cows, 0, 20);
}
return array_sum($cows);
}