递归算法示例:
Python
def Fibonacci(n): if n==0: return 0 if n==1: return 1 else: return Fibonacci(n-1) + Fibonacci(n-2) print(Fibonacci(7))
PHP
<?php function Fibonacci($n) { if ( $n == 0) return 0; if ( $n == 1) return 1; return Fibonacci($n-1) + Fibonacci($n-2); } echo Fibonacci(10);
非递归实现:
Python
def Fibonacci(n): a,b = 1,1 for i in range(n-1): a,b = b,a+b return a print(Fibonacci(8))