Merge pull request #65 from prondubuisi/feature/make-factorial-cached

Add cache improvements for factorial solution
This commit is contained in:
Brandon Johnson 2022-07-08 12:24:29 -06:00 committed by GitHub
commit 9e297581ac
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

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;
}