This article mainly introduces the PHP implementation Fibonacci sequence code sharing, has a certain reference value, the need for friends can refer to, hope to help everyone.
The Fibonacci sequence refers to a sequence of 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 with the 3rd item and each item is equal to the sum of the first two items.
F0=0,f1=1,fn=f (n-1) +f (n-2)
Recursive and non-recursive versions.
<?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 (?>)
As the C and Java program Ape, the first time in the write non-recursive, forget the variable before adding $, sad reminder.
Output results
Array ( [0] = 1 [1] = 1 [2] = 2 [3] = 3 [4] = 5 [5] = 8 [6] = = 13
[7] [8] = [ 9] = +)------------------55
The percussion society? Give it a try.