Skip to content

Instantly share code, notes, and snippets.

@mtdowling
Created January 12, 2013 07:42
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mtdowling/4516616 to your computer and use it in GitHub Desktop.
Save mtdowling/4516616 to your computer and use it in GitHub Desktop.
Various methods of calculating Fibonacci numbers in PHP
<?php
/**
* Various methods of computing Fibonacci numbers in PHP
*/
class Fibonacci
{
/**
* @var array Memoization cache
* @see Fibonacci::memoized
*/
protected $cache = array(0 => 0, 1 => 1);
/**
* Fibonacci using recursion
*/
public function recursive($n)
{
if ($n == 0) {
return 0;
}
if ($n == 1) {
return 1;
}
return $this->recursive($n - 1) + $this->recursive($n - 2);
}
/**
* Fibonacci using an iterative approach
*/
public function iterative($n)
{
$a = 0;
$b = 1;
for ($i = 0; $i < $n; $i++) {
$c = $a;
$a = $b;
$b += $c;
}
return $a;
}
/**
* Fibonacci using Binet's formula
* @link http://mathworld.wolfram.com/BinetsFibonacciNumberFormula.html
*/
public function binet($n)
{
$phi = (1 + sqrt(5)) / 2;
return (pow($phi, $n) - pow(1 - $phi, $n)) / sqrt(5);
}
/**
* Fibonacci using a cache
*/
public function memoized($n)
{
if (!isset($this->cache[$n])) {
$this->cache[$n] = $this->memoized($n - 1) + $this->memoized($n - 2);
}
return $this->cache[$n];
}
}
/**
* Test each Fibonacci method and output the speed
*/
function test($total, $callback)
{
echo $callback[1] . ":\n";
$t = microtime(true);
for ($x = 0; $x < $total; $x++) {
call_user_func($callback, $x);
}
$finish = microtime(true) - $t;
echo ($finish * 1000) . ' ms (' . (($finish / $total) * 1000) . ")\n\n";
}
// You can pass in the total number of sequences to calculate as a CLI argument
$total = isset($argv[1]) ? $argv[1] : 25;
$fib = new Fibonacci();
test($total, array($fib, 'iterative'));
test($total, array($fib, 'binet'));
test($total, array($fib, 'memoized'));
// Limit our attempts with recursion
if ($total <= 30) {
test($total, array($fib, 'recursive'));
}
@shadowhand
Copy link

shadowhand commented Oct 16, 2017

Thank you, this was super useful. Here's the results for anyone interested: https://3v4l.org/5ksoN

@mohdbred
Copy link

mohdbred commented Jun 3, 2018

You really explained very well. All the algorithms and formulas are included to calculate the Fibonacci Series. Helped a lot.

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