Fibonacci Calculator

From MFSP Wiki

Jump to: navigation, search

The script for the Fibonacci number generator. This script is the fastest one I have found as of yet.

<?php

function Fibonacci($number) {
    if ($number < 1) {
        return false;
    }

    $result[0] = 0;
    $result[1] = 1;
    $result[2] = 1;

    for ($i = 3; $i <= $number; $i++) {
        $result[$i] = bcadd($result[$i - 1], $result[$i - 2]);
        unset($result[$i - 3]);
        if ($i == $number) {
            return $result[$i];
        }
    }
}

?>

Time to calculate:

10:    0.00102 sec.,      2 digits
50:    0.00111 sec.,     11 digits
100:   0.00118 sec.,     21 digits 
250:   0.00159 sec.,     52 digits
500:   0.00279 sec.,    105 digits
1000:  0.00505 sec.,    209 digits
2500:  0.01871 sec.,    523 digits
5000:  0.06050 sec.,   1045 digits
10000: 0.22043 sec.,   2090 digits
20000: 0.81250 sec.,   4180 digits
30000: 1.77865 sec.,   6270 digits
40000: 3.12176 sec.,   8360 digits
50000: 4.85685 sec.,  10450 digits

If you have found a faster one, please let me know.

As with all scripts here, if you re-distribute the code, I ask that you simply include the following comments beforehand:

# Script by Andre Kessler for MathForSmartyPants.com, some rights reserved. 
# See http://creativecommons.org/licenses/by-nc-sa/3.0/ for more info.
# Please leave these comments in the script if you re-distribute them.
Personal tools