forked from keon/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
factorial.py
32 lines (30 loc) · 1.03 KB
/
factorial.py
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
def factorial(n, mod=None):
"""Calculates factorial iteratively.
If mod is not None, then return (n! % mod)
Time Complexity - O(n)"""
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, mod=None):
"""Calculates factorial recursively.
If mod is not None, then return (n! % mod)
Time Complexity - O(n)"""
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