Add cache improvements

This commit is contained in:
Ndubuisi Onyemenam 2022-07-07 01:59:59 +01:00
parent ca49219469
commit a4840d116d

View File

@ -10,11 +10,21 @@
*/
function factorial(int $number)
{
static $cache = [];//internal caching memory for speed
if ($number < 0) {
throw new \Exception("Negative numbers are not allowed for calculating Factorial");
}
if ($number === 0) {
return 1; // Factorial of 0 is 1
}
return ($number * factorial($number - 1)); // Recursion since x! = x * (x-1)!
if (isset($cache[$number])) {
return $cache[$number];
}
$fact = ($number * factorial($number - 1)); // Recursion since x! = x * (x-1)!
$cache[$number] = $fact;
return $fact;
}