1 <?php 2 #Fibonacci数列问题 3 #f(1) = 1 4 #f(n) = f(n - 1) + f(n - 2) 5 #求f(n) 6 7 #递归方法 8 function fibonacci($n) { 9 if ($n == 0) { 10 return 0; 11 } 12 13 if ($n == 1) { 14 return 1; 15 } 16 17 return fibonacci($n - 1) + fibonacci($n - 2); 18 } 19 20 #非递归方法 21 function fibonacci_norec($n) { 22 $a = 0; 23 $b = 1; 24 25 for ($i = 2; $i <= $n; $i++) { 26 $c = $a + $b; 27 $a = $b; 28 $b = $c; 29 } 30 31 return $c; 32 } 33 34 echo fibonacci(10); 35 echo "<br>"; 36 echo fibonacci_norecr(10); 37 ?>
![](https://img2024.cnblogs.com/blog/35695/202408/35695-20240826070647288-243310440.jpg)