mirror of
https://github.com/TheAlgorithms/PHP.git
synced 2025-07-06 17:53:50 +02:00
Add cache improvements
This commit is contained in:
@ -10,11 +10,21 @@
|
|||||||
*/
|
*/
|
||||||
function factorial(int $number)
|
function factorial(int $number)
|
||||||
{
|
{
|
||||||
|
static $cache = [];//internal caching memory for speed
|
||||||
|
|
||||||
if ($number < 0) {
|
if ($number < 0) {
|
||||||
throw new \Exception("Negative numbers are not allowed for calculating Factorial");
|
throw new \Exception("Negative numbers are not allowed for calculating Factorial");
|
||||||
}
|
}
|
||||||
if ($number === 0) {
|
if ($number === 0) {
|
||||||
return 1; // Factorial of 0 is 1
|
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;
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user