Recursive function cattle for the ox

Source: Internet
Author: User
<?php
/*
* There is a cow, to four years old can bear, each year, the birth is the same cow, 15-year-old sterilization, 20-year-old death
* How many cows are there after n years?
* The subject needs to be calculated using Recursive functions
* Condition 1: When the cattle are 4-15 years old, they can be born
* Condition 2: When the ox dies at the age of 20
*/

$n for years
function sum ($n)
{
Define a count result
static $num = 1;
Start the cycle to determine the age of the cow
for ($i =1; $i <= $n; $i + +)
{
if ($i >=4&& $i <15)
{
Fertile year can be born
$num + +;
Judging how many children can be born this year, to meet the conditions, the same plus, no
SUM ($n-$i);
}
When he was 20 years old, he died.
if ($i = = 20)
{
$num--;
}
}
return $num;
}

echo sum (10);


Summary: The subject of a bit dizzy, in fact, is not difficult, after must be a lot of practice. With recursive functions, the number of cows is calculated, two conditions, recursive

This year, a few can be born, each call is a cow's age, when reaching 4 years old, fertile, 15 years old, not born, 20-year-old death.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.