Last active
April 3, 2018 10:14
-
-
Save navidanindya/a8d38b0d3df1ef12fcfd473ff07e231b to your computer and use it in GitHub Desktop.
Memoized Fibonacci and Factorial in PHP. Test: https://repl.it/repls/HilariousImpishProgrammingtool
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function factorial($number, $memoize = array(0,1)) { | |
if ($number == 0 || $number == 1) { | |
return 1; | |
} | |
if (!array_key_exists($number, $memoize)) { | |
$memoize[$number] = $number * factorial($number-1, $memoize); | |
} | |
return $memoize[$number]; | |
} | |
function fibonacci ($number, $memoize = array(0,1)) { | |
if ($number == 0) { | |
return 0; | |
} else if ($number == 1 || $number == 2) { | |
return 1; | |
} else { | |
if (!array_key_exists($number, $memoize)) { | |
$memoize[$number] = fibonacci($number-1) + fibonacci($number-2); | |
} | |
return $memoize[$number]; | |
} | |
} | |
echo "Factorial of 6: ".factorial(6)."\n"; | |
echo "Fibonacci of 7: ".fibonacci(7)."\n"; | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment