forked from TheAlgorithms/PHP
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFactorial.php
More file actions
36 lines (29 loc) · 730 Bytes
/
Factorial.php
File metadata and controls
36 lines (29 loc) · 730 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<?php
/**
* This function calculates
* and returns the factorial
* of provided positive integer
* number.
*
* @param Integer $number Integer input
* @return Integer Factorial of the input
* @throws \Exception
*/
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");
}
// Factorial of 0 is 1
if ($number === 0) {
return 1;
}
if (isset($cache[$number])) {
return $cache[$number];
}
// Recursion since x! = x * (x-1)!
$fact = ($number * factorial($number - 1));
$cache[$number] = $fact;
return $fact;
}