forked from TheAlgorithms/Python
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdouble_factorial.py
More file actions
Latest commit
60 lines (51 loc) · 2.03 KB
/
Copy pathdouble_factorial.py
File metadata and controls
60 lines (51 loc) · 2.03 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
defdouble_factorial_recursive(n: int) ->int:
"""
Compute double factorial using recursive method.
Recursion can be costly for large numbers.
To learn about the theory behind this algorithm:
https://en.wikipedia.org/wiki/Double_factorial
>>> from math import prod
>>> all(double_factorial_recursive(i) == prod(range(i, 0, -2)) for i in range(20))
True
>>> double_factorial_recursive(0.1)
Traceback (most recent call last):
...
ValueError: double_factorial_recursive() only accepts integral values
>>> double_factorial_recursive(-1)
Traceback (most recent call last):
...
ValueError: double_factorial_recursive() not defined for negative values
"""
ifnotisinstance(n, int):
raiseValueError("double_factorial_recursive() only accepts integral values")
ifn<0:
raiseValueError("double_factorial_recursive() not defined for negative values")
return1ifn<=1elsen*double_factorial_recursive(n-2)
defdouble_factorial_iterative(num: int) ->int:
"""
Compute double factorial using iterative method.
To learn about the theory behind this algorithm:
https://en.wikipedia.org/wiki/Double_factorial
>>> from math import prod
>>> all(double_factorial_iterative(i) == prod(range(i, 0, -2)) for i in range(20))
True
>>> double_factorial_iterative(0.1)
Traceback (most recent call last):
...
ValueError: double_factorial_iterative() only accepts integral values
>>> double_factorial_iterative(-1)
Traceback (most recent call last):
...
ValueError: double_factorial_iterative() not defined for negative values
"""
ifnotisinstance(num, int):
raiseValueError("double_factorial_iterative() only accepts integral values")
ifnum<0:
raiseValueError("double_factorial_iterative() not defined for negative values")
value=1
foriinrange(num, 0, -2):
value*=i
returnvalue
if__name__=="__main__":
importdoctest
doctest.testmod()