斐波那契数列实现的2种方法
// 递归法: 斐波那契数列
function fab1($n)
{
if ($n <= 0) {
return 0;
}
if ($n == 0 || $n == 1) {
return $n;
}
return fab1($n - 1) + fab1($n - 2);
}
// 优化
function fab($n)
{
$first = 0;
$second = 1;
$next_value = 0;
for ($i = 2; $i <= $n; $i++) {
$next_value = $first + $second;
$first = $second;
$second = $next_value;
}
return $next_value;
}