This article mainly introduces the code sharing of Fibonacci sequence in PHP. It has certain reference value. Friends in need can refer to it.
The Fibonacci sequence refers to a sequence of numbers 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597 , 2584, 4181, 6765, 10946, 17711, 28657, 46368...
This sequence starts from the 3rd item, and each item is equal to the sum of the previous two items.
F0=0, F1=1, Fn=F(n-1) F(n-2)
Recursive version and non-recursive version.
<?php function fib($n){ $array = array(); $array[0] = 1; $array[1] = 1; for($i=2;$i<$n;$i++){ $array[$i] = $array[$i-1]+$array[$i-2]; } print_r($array); } fib(10); echo "\n------------------\n"; function fib_recursive($n){ if($n==1||$n==2){return 1;} else{ return fib_recursive($n-1)+fib_recursive($n-2); } } echo fib_recursive(10); ?>
As a C and Java programmer, the first time I wrote non-recursive code, I forgot to add $ before the variable, which is very sad.
Output results
Array ( [0] => 1 [1] => 1 [2] => 2 [3] => 3 [4] => 5 [5] => 8 [6] => 13 [7] => 21 [8] => 34 [9] => 55 ) ------------------ 55
Summary
The above is about this article PHP implements the entire Fibonacci sequence code sharing, I hope it will be helpful to everyone. Interested friends can continue to refer to other related topics on this site. If there are any shortcomings, please leave a message to point out. Thank you friends for your support of php Chinese website!
Example explanation of PHP implementation of array search function based on dichotomy
Detailed explanation of classes and objects in php
##Explanation of PHP single file and multiple file upload examples
The above is the detailed content of PHP implementation of Fibonacci sequence code sharing. For more information, please follow other related articles on the PHP Chinese website!