forked from keon/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfactorial.py
More file actions
76 lines (60 loc) · 1.84 KB
/
factorial.py
File metadata and controls
76 lines (60 loc) · 1.84 KB
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
"""
Factorial
Compute the factorial of a non-negative integer, with optional modular
arithmetic support.
Reference: https://en.wikipedia.org/wiki/Factorial
Complexity:
Time: O(n)
Space: O(1) iterative, O(n) recursive
"""
from __future__ import annotations
def factorial(n: int, mod: int | None = None) -> int:
"""Calculate n! iteratively, optionally modulo mod.
Args:
n: A non-negative integer.
mod: Optional positive integer modulus.
Returns:
n! or n! % mod if mod is provided.
Raises:
ValueError: If n is negative or mod is not a positive integer.
Examples:
>>> factorial(5)
120
>>> factorial(10)
3628800
"""
if not (isinstance(n, int) and n >= 0):
raise ValueError("'n' must be a non-negative integer.")
if mod is not None and not (isinstance(mod, int) and mod > 0):
raise ValueError("'mod' must be a positive integer")
result = 1
if n == 0:
return 1
for i in range(2, n + 1):
result *= i
if mod:
result %= mod
return result
def factorial_recur(n: int, mod: int | None = None) -> int:
"""Calculate n! recursively, optionally modulo mod.
Args:
n: A non-negative integer.
mod: Optional positive integer modulus.
Returns:
n! or n! % mod if mod is provided.
Raises:
ValueError: If n is negative or mod is not a positive integer.
Examples:
>>> factorial_recur(5)
120
"""
if not (isinstance(n, int) and n >= 0):
raise ValueError("'n' must be a non-negative integer.")
if mod is not None and not (isinstance(mod, int) and mod > 0):
raise ValueError("'mod' must be a positive integer")
if n == 0:
return 1
result = n * factorial(n - 1, mod)
if mod:
result %= mod
return result