Home  >  Article  >  Backend Development  >  Recursive function to calculate the Year of the Ox

Recursive function to calculate the Year of the Ox

潜轲
潜轲Original
2017-08-17 22:38:061422browse

/*
* There is a cow that can give birth until the age of four. One cow is born every year. She gives birth to the same cow. She is sterilized at the age of 15 and dies at the age of 20.
* How many cows will there be after n years
* This question requires the use of a recursive function to calculate
* Condition 1: When the cow is 4-15 years old, it can give birth
* Condition 2: When the cow dies at the age of 20
*/

//$n is the number of years
function sum($n)
{
//Define a counting result
static $num = 1;
//Start the loop to determine the age of the cow
for($i=1;$i<=$n;$i++)
{
 if($i>=4&&$i<15)
                                                                                                                                                                                                                                                         $num++; i);
                                  
                                                                                                                                                                                                                                                          ## return $num;
}

echo sum(10);





//Summary: This question is a bit confusing at first glance. It's actually not very difficult, and you will have to practice more in the future. This question uses a recursive function to calculate the number of cows. Two conditions, recursive judgment

//Determine how many cows can be born this year. Each call is the age of a cow. When it reaches 4 years old, it is fertile. At the age of 15, he was barren and died at the age of 20.


The above is the detailed content of Recursive function to calculate the Year of the Ox. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn