Skip to content

Instantly share code, notes, and snippets.

@arvindsvt
Created February 25, 2018 07:04
Show Gist options
  • Save arvindsvt/bfc59e936de8700726abb90fc5bd60b7 to your computer and use it in GitHub Desktop.
Save arvindsvt/bfc59e936de8700726abb90fc5bd60b7 to your computer and use it in GitHub Desktop.
class Fib{
//$memo and fibonacciMemo are static members
static $memo = array();
static function fibonacciMemo($n) {
if(array_key_exists($n, static::$memo)) {
return static::$memo[$n];
}
else {
if($n > 1) {
$result = static::fibonacciMemo($n-1) + static::fibonacciMemo($n-2);
static::$memo[$n] = $result;
return $result;
}
return $n;
}
}
}
//Using the same method by Edd Mann to benchmark
//the results
$start = microtime(true);
Fib::fibonacciMemo(10);
echo sprintf("%f\n", microtime(true) - $start);
//outputs 0.000249
$start = microtime(true);
Fib::fibonacciMemo(10);
echo sprintf("%f\n", microtime(true) - $start);
//outputs 0.000016 (now with memoized fibonacci)
//Cleaning $memo
Fib::$memo = array();
$start = microtime(true);
Fib::fibonacciMemo(10);
echo sprintf("%f\n", microtime(true) - $start);
//outputs 0.000203 (after 'cleaning' $memo)
https://stackoverflow.com/questions/28870968/memoizing-fibonacci-function-in-php
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment