A cow, a cow and a bull at the end of the second, a cow at the end of the year, and a cow at the beginning of the third. Bulls can only live for four years. A farm began with only a newborn cow, n years after the total number of cattle. Please write a function output, recursive and non-recursive two methods to achieve. function Cowrecursion ($i) {if ($i = = 1)//If it is the first year, then 1 cows. {return 1;} ElseIf ($i = = 2) {return 2 + cowrecursion (1);//First Cow and Sons + second cow first year}elseif ($i = = 3) {return 2 + cowrecursion (2) + Cowrecursio n (1); First Cow and Sons + Second cow second year + third cow first year}elseif ($i ==4) {return 2 + cowrecursion (3) + cowrecursion (2); First Cow and Sons + Second cow third year + third cow second year}//elseif ($i = = 5)//{//Return Cowrecursion (4) + cowrecursion (3); The first cow died. The bull is dead, too. Second cow, year four + third cow third year//}elseif ($i >= 5) {return cowrecursion ($i-1) + cowrecursion ($i-2); }}//non-recursive implementation of function Cow_norecursion ($i) {///implement ideas, stored in an array, value of values represents the age. Loop plus 1. $cows = Array (1); In the first year, 1 cows. $cowsmale = Array (); Used to store bull for ($j =0; $j < $i; $j + +)//cycle for years {//Cycle cows $cows _copy = $cows; foreach ($cows as $key + = $value) {switch ($cows _cop y[$key]) {case 1:break;case 2: $cows _copy[] = 1; $cowsmale [] = 1; Break;case 3: $cows _copy[] = 1; Break;case 4:break;case 5:unset($cows _copy[$key]); Break;}} $cows = $cows _copy;array_walk ($cows, function (& $value, $index) {if ($value > 0) $value + +;}); $cowsmale _copy = $cowsmale; Cyclic bull foreach ($cowsmale as $d + $value) {$cowsmale _copy[$d]++;if ($cowsmale _copy[$d] = = 5)//By the end of the year {unset ($cow smale_copy[$d]); }} $cowsmale = $cowsmale _copy; }return count ($cows) + count ($cowsmale); }echo "
List Totol---> ". cow_norecursion (+); echo"
Totol recursion---> ". cowrecursion (26);
End
This paper introduces the recursive algorithm and non-recursive algorithm of the cow's offspring. , including the aspects of the content, want to be interested in PHP tutorial friends helpful.