mirror of
https://github.com/TheAlgorithms/PHP.git
synced 2025-01-17 07:08:13 +01:00
Merge pull request #65 from prondubuisi/feature/make-factorial-cached
Add cache improvements for factorial solution
This commit is contained in:
commit
9e297581ac
@ -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;
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user