diff --git a/Maths/Factorial.php b/Maths/Factorial.php index 25cba1b..8dc08c9 100644 --- a/Maths/Factorial.php +++ b/Maths/Factorial.php @@ -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; }