PHP 與斐波那契數列

chaofei發表於2018-09-04

三種方式實現斐波那契數列

普通遞迴實現

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
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章