PHP Solves the Rabbit Born Rabbit Problem Based on Recursive Algorithm

  • 2021-09-24 21:54:10
  • OfStack

In this paper, an example is given to solve the problem of rabbit giving birth to rabbit based on recursive algorithm in PHP. Share it for your reference, as follows:

After receiving the interview notice, I tossed and turned, and I was meditating on how to introduce my project experience tomorrow.

Get up early, wash, and ask yourself some questions about your summary.

After eating breakfast in a hurry, I squeezed into the subway with a ferocious face. At this time, I ignored everything and only looked forward to getting off the subway quickly. Finally, I arrived at the interview place half an hour in advance, took out the prepared questions again and looked at them a few times, with 15 minutes left to go up. Then I filled out the form by manpower and gave me an algorithm problem.

As follows: There is a pair of rabbits, from the third month after birth, a pair of rabbits are born every month, and a pair of rabbits are born every month after the third month. If rabbits are not dead, please program and output the total number of rabbits every month within two years.

Suddenly, I remembered that a friend who had talked with me before this problem had a similar idea.

The first method (for loop implementation):


<?php
  function getResult($month){
   $one = 1; // No. 1 1 Logarithm of rabbits in months 
   $two = 1; // No. 1 2 Logarithm of rabbits in months 
   $sum = 0; // No. 1 $month Logarithm of rabbits in months 
   if($month < 3){
     return ;
     }
   for($i = 2;$i < $month; $i++){
     $sum = $one + $two;
     $one = $two;
     $two = $sum;
   }
   echo $month.' Total after 6 months '.$sum.' To rabbits ';
  }
// Test: 
getResult(8)
// Output: 8 Total after 6 months 21 To rabbits 

Method 2 (recursion):


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

Afterwards, I also looked it up on the Internet, but most of the code examples are in C, c + +, java and so on. There are not too many PHP-related code examples, these two methods, I hope to help you.

In fact, the whole interview process was quite tense, but it was beautiful in the end. No, the second interview notice is coming. Thanks to the elder brother of Qianfeng PHP.

For more readers interested in PHP related contents, please check the topics of this site: "PHP Data Structure and Algorithm Tutorial", "php Programming Algorithm Summary", "php String (string) Usage Summary", "PHP Array (Array) Operation Skills Complete Book", "PHP Common Traversal Algorithms and Skills Summary" and "PHP Mathematical Operation Skills Summary"

I hope this article is helpful to everyone's PHP programming.


Related articles: