2

Simple version of the Fibonacci sequence:

<?php

function fibonacci($n) {

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

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

n is less than 10, and the performance is acceptable. n takes large numbers, and the usage time soars. Optimize it, exchange space for time, and reuse the calculated results in the array.

<?php

function fibonacci($n) {
    static $cache = [];

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

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

    $temp = fibonacci($n-1) + fibonacci($n-2);
    $cache[$n] = $temp;
    return $temp;
}

Now the performance is enough, but if the number fetched by n is very large, which is beyond the range of integer or floating point, it is necessary to use string storage instead. To implement vertical addition.

<?php
function fibonacci($n) {
    static $cache = [];

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

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

    $temp = stringAdd(fibonacci($n-1), fibonacci($n-2));
    $cache[$n] = $temp;
    return $temp;
}

function stringAdd($s1, $s2) {
    $s1 = strval($s1);
    $s2 = strval($s2);
    $s1Length = strlen($s1);
    $s2Length = strlen($s2);
    $length = 0;

    if ($s1Length > $s2Length) {
        $length = $s1Length;
        $s2 = str_pad($s2, $s1Length, '0', STR_PAD_LEFT);
    } else {
        $length = $s2Length;
        $s1 = str_pad($s1, $s2Length, '0', STR_PAD_LEFT);
    }

    $returnRes = '';
    $carry = 0;
    for ($i=$length-1; $i>=0; $i--) {
        $result = intval($s1[$i]) + intval($s2[$i]) + $carry;
        $res = $result % 10;
        $carry = floor($result / 10);

        $returnRes = $res . $returnRes;
    }

    if ($carry > 0) {
        return strval($carry) . $returnRes;
    }

    return $returnRes;
}

final algorithm.


church
3.6k 声望67 粉丝