Home  >  Article  >  Backend Development  >  How to write php rabbit problem code

How to write php rabbit problem code

爱喝马黛茶的安东尼
爱喝马黛茶的安东尼Original
2019-09-26 16:02:403477browse

How to write php rabbit problem code

is as follows: There is a pair of rabbits. From the third month after birth, they give birth to a pair of rabbits every month. After the rabbit grows to the third month, they give birth to another pair every month. For rabbits, if the rabbits do not die, please program to output the total number of rabbits in each month within two years?

Related recommendations: "php Getting Started Tutorial"

The first method (for loop implementation):

<?php
  function getResult($month){
   $one = 1; //第一个月兔子的对数
   $two = 1; //第二个月兔子的对数
   $sum = 0; //第$month个月兔子的对数
   if($month < 3){
     return ;
     }
   for($i = 2;$i < $month; $i++){
     $sum = $one + $two;
     $one = $two;
     $two = $sum;
   }
   echo $month.&#39;个月后共有&#39;.$sum.&#39;对兔子&#39;;
  }
//测试:
getResult(8)
//输出:8个月后共有21对兔子

Second method (recursive):

<?php
function fun($n){
  if($n == 1 || $n == 2){
    return 1;
  }else{
    return fun($n-1)+fun($n-2);
  }
}
//测试:
echo fun(8)
//输出:21

The above is the detailed content of How to write php rabbit problem code. 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