PHP 与斐波那契数列

三种方式实现斐波那契数列

普通递归实现

function fibonacci_recursive($n) {
    if ($n <= 1) {
        return 1;
    }

    return fibonacci_recursive($n - 1) + fibonacci_recursive($n - 2);
}

for ($i = 1; $i <= 30; $i++) {
   echo fibonacci_recursive($i) . "  ";
}

耗时
3.52s user 0.00s system 99% CPU 3.521 total

递归优化,增加内存缓存

function fibonacci_recursive_optimization($n) {
    static $caches_arr = [];

    if (isset($caches_arr [$n])) {
        return $caches_arr [$n];
    }

    if ($n <= 1) {
        $res = 1;
    } else {
        $res = fibonacci_recursive_optimization($n - 1) + fibonacci_recursive_optimization($n - 2);
    }

    $caches_arr [$n] = $res;

    return $res;
}

for ($i = 1; $i <= 30; $i++) {
    echo fibonacci_recursive_optimization($i) . "  ";
}

耗时
0.01s user 0.01s system 98% CPU 0.022 total

闭包实现

function fibonacci_closure() {
    static $x = 0;
    static $y = 1;
    return function () use (&$x, &$y) {
        [$x, $y] = [$y, $x + $y];
        return $y;
    };
}

$f = fibonacci_closure();
for ($i = 1; $i <= 30; $i++) {
    echo $f() . " ";
}

耗时
0.02s user 0.01s system 99% CPU 0.030 total

发表评论