Skip to content

Commit 83f185a

Browse files
Added factorial_recursive.py with doctests and descriptive parameter name
1 parent e2a78d4 commit 83f185a

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

maths/factorial_recursive.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
"""
2+
Recursive factorial implementation.
3+
4+
Reference: https://en.wikipedia.org/wiki/Factorial
5+
"""
6+
7+
def factorial(number: int) -> int:
8+
"""
9+
Calculate the factorial of a non-negative integer recursively.
10+
11+
Parameters:
12+
number (int): A non-negative integer whose factorial is to be calculated.
13+
14+
Returns:
15+
int: The factorial of the input number.
16+
17+
Raises:
18+
ValueError: If the input number is negative.
19+
20+
Examples:
21+
>>> factorial(0)
22+
1
23+
>>> factorial(1)
24+
1
25+
>>> factorial(5)
26+
120
27+
"""
28+
if number < 0:
29+
raise ValueError("number must be non-negative")
30+
if number <= 1:
31+
return 1
32+
return number * factorial(number - 1)
33+
34+
35+
if __name__ == "__main__":
36+
print(factorial(5))

0 commit comments

Comments
 (0)