Home > Article > Backend Development > 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.'个月后共有'.$sum.'对兔子'; } //测试: 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!