斐波那契数列 php

// 递归
$len = 20;
function f($a)
{
    if ($a == 1 || $a == 2) {
        return 1;
    }
    return f($a-1) + f($a-2);
}
var_dump(f($len));

// 数组
function test($num)
{
    $arr = [];
    for ($i = 0; $i < $num; $i++)
    {
        if ($i == 0 || $i == 1)
        {
            $arr[$i] = 1;
        }
        else
        {
            $arr[$i] = $arr[$i - 1] + $arr[$i - 2];
        }
    }
    return $arr[$num-1];
}
var_dump(test($len));

// yield
function fb($max)
{
    $n = 0;
    $a = 0;
    $b = 1;
    while ($n < $max)
    {
        if ($n != 1)
        {
            $r = $a + $b;
            $a = $b;
            $b = $r;
        }
        else
        {
            $r = 1;
        }
        $n++;
        yield $r;
    }
}
foreach (fb($len) as $key => $i)
{
    if ($key != $len - 1)
    {
        continue;
    }
    var_dump($i);
}

相关文章

此处评论已关闭