This article mainly introduces PHP based on recursive algorithm to solve rabbits rabbit rabbit problem, combined with the case of the rabbit born Rabbit problem php face questions using the cycle and recursive two ways to solve the idea, the need for friends can refer to the next
In this paper, we explain the problem that PHP solves rabbits ' rabbit-born rabbits based on recursive algorithm. Share to everyone for your reference, as follows:
Received the interview notice tossing and turning, has been in meditation tomorrow how to introduce their own project experience.
Early to get up, wash, and their own summary of the question self-answer some.
Hurriedly eat breakfast, squeeze into let people grim face subway, at this time what all disregard, only hope to hurriedly down the subway. Finally half an hour early to the interview site, again to take the preparation of the question to see a few eyes, and left 15 minutes up. Fill in the form with the manpower, and then give me an algorithm problem.
as follows : There are a pair of rabbits, from the 3rd month after birth a pair of rabbits each month, the small rabbit after the third month after the birth of a pair of rabbits, if the rabbit is not dead, please program output two years each month the total number of rabbits?
Suddenly remember, this question before a friend talked to me, the idea is the same.
The first method (for loop implementation):
<?php function GetResult ($month) { $one = 1;//The logarithm of the rabbit for the first month $two = 1;//////The logarithm of the rabbit for the second month $sum = 0; Logarithm of month rabbit if ($month < 3) { return; } for ($i = 2; $i < $month; $i + +) { $sum = $one + $two; $one = $two; $two = $sum; } echo $month. ' Total in a month '. $sum. ' Against rabbits '; } Test: GetResult (8)//output: 8 months later a total of 21 pairs of rabbits
The second method (recursion):
<?phpfunction Fun ($n) { if ($n = = 1 | | $n = = 2) { return 1; } else{ return Fun ($n-1) +fun ($n-2);} } Test: Echo Fun (8)//output: 21
After that, I went online, but most of the code examples are in C, C + +, Java, and so on. And there are not too many PHP-related code examples, both methods, hope can help everyone.
In fact, the whole interview process is very tense, fortunately, the final finish is very beautiful. This is not, the second-round notice came, thank that thousand front php buddy.
Articles you may be interested in:
About exception handling in thinkphp _php instance
PHP7 PHP tips for uploading images based on curl
php5.0~5.6 version Compatibility Curl File Upload Function example analysis PHP tips