Skip to content

Instantly share code, notes, and snippets.

@andrewdalpino
Last active March 8, 2018 09:47
Show Gist options
  • Save andrewdalpino/71344f86c1802866d8a9961d5fb89339 to your computer and use it in GitHub Desktop.
Save andrewdalpino/71344f86c1802866d8a9961d5fb89339 to your computer and use it in GitHub Desktop.
<?php
$results = [];
$results[0] = gmp_init(1);
$results[1] = gmp_init(1);
$n = $argv[1] ?? 1000;
if ($n < 2 || $n > PHP_INT_MAX) {
throw new InvalidArgumentException('N cannot be less than 2 or greater than ' . number_format(PHP_INT_MAX) . '.');
}
echo 'Generating ' . number_format($n) . ' Fibonacci numbers ... ';
$start = microtime(true);
foreach (range(2, $n - 1) as $i) {
$fib = gmp_add($results[$i - 2], $results[$i - 1]);
$results[$i] = $fib;
}
echo 'done in ' . (string) round(microtime(true) - $start, 5) . ' seconds.' . "\n";
readline('Press any key to dump results ... ');
var_dump($results);
@andrewdalpino
Copy link
Author

Results:
Generating 1,000 Fibonacci numbers ... done in 0.00045 seconds.

This is the 1000th Fibonacci number

434665576869374564356885276750406258025646605173717804024817290895365554179490518904038798
40079255169295922593080322634775209689623239873322471161642996440906533187938298969649928516003704476137795
166849228875

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment