2021-10-21 07:06:32 +00:00
|
|
|
"""Factorial of a positive integer -- https://en.wikipedia.org/wiki/Factorial
|
|
|
|
"""
|
2020-01-18 13:06:48 +00:00
|
|
|
|
|
|
|
|
2021-10-21 07:06:32 +00:00
|
|
|
def factorial(number: int) -> int:
|
2020-01-18 13:06:48 +00:00
|
|
|
"""
|
2021-10-21 07:06:32 +00:00
|
|
|
Calculate the factorial of specified number (n!).
|
|
|
|
|
2020-01-18 13:06:48 +00:00
|
|
|
>>> import math
|
|
|
|
>>> all(factorial(i) == math.factorial(i) for i in range(20))
|
|
|
|
True
|
|
|
|
>>> factorial(0.1)
|
|
|
|
Traceback (most recent call last):
|
|
|
|
...
|
|
|
|
ValueError: factorial() only accepts integral values
|
|
|
|
>>> factorial(-1)
|
|
|
|
Traceback (most recent call last):
|
|
|
|
...
|
|
|
|
ValueError: factorial() not defined for negative values
|
2021-10-21 07:06:32 +00:00
|
|
|
>>> factorial(1)
|
|
|
|
1
|
|
|
|
>>> factorial(6)
|
|
|
|
720
|
|
|
|
>>> factorial(0)
|
|
|
|
1
|
2020-01-18 13:06:48 +00:00
|
|
|
"""
|
2021-10-21 07:06:32 +00:00
|
|
|
if number != int(number):
|
2020-01-18 13:06:48 +00:00
|
|
|
raise ValueError("factorial() only accepts integral values")
|
2021-10-21 07:06:32 +00:00
|
|
|
if number < 0:
|
2020-01-18 13:06:48 +00:00
|
|
|
raise ValueError("factorial() not defined for negative values")
|
|
|
|
value = 1
|
2021-10-21 07:06:32 +00:00
|
|
|
for i in range(1, number + 1):
|
2020-01-18 13:06:48 +00:00
|
|
|
value *= i
|
|
|
|
return value
|
|
|
|
|
|
|
|
|
2023-01-26 07:12:11 +00:00
|
|
|
def factorial_recursive(n: int) -> int:
|
|
|
|
"""
|
|
|
|
Calculate the factorial of a positive integer
|
|
|
|
https://en.wikipedia.org/wiki/Factorial
|
|
|
|
|
|
|
|
>>> import math
|
|
|
|
>>> all(factorial(i) == math.factorial(i) for i in range(20))
|
|
|
|
True
|
|
|
|
>>> factorial(0.1)
|
|
|
|
Traceback (most recent call last):
|
|
|
|
...
|
|
|
|
ValueError: factorial() only accepts integral values
|
|
|
|
>>> factorial(-1)
|
|
|
|
Traceback (most recent call last):
|
|
|
|
...
|
|
|
|
ValueError: factorial() not defined for negative values
|
|
|
|
"""
|
|
|
|
if not isinstance(n, int):
|
|
|
|
raise ValueError("factorial() only accepts integral values")
|
|
|
|
if n < 0:
|
|
|
|
raise ValueError("factorial() not defined for negative values")
|
2023-07-22 10:05:10 +00:00
|
|
|
return 1 if n in {0, 1} else n * factorial(n - 1)
|
2023-01-26 07:12:11 +00:00
|
|
|
|
|
|
|
|
2020-01-18 13:06:48 +00:00
|
|
|
if __name__ == "__main__":
|
2021-10-21 07:06:32 +00:00
|
|
|
import doctest
|
|
|
|
|
|
|
|
doctest.testmod()
|
|
|
|
|
2020-03-04 12:40:28 +00:00
|
|
|
n = int(input("Enter a positive integer: ").strip() or 0)
|
2020-01-18 13:06:48 +00:00
|
|
|
print(f"factorial{n} is {factorial(n)}")
|