Skip to content

Commit 4761fef

Browse files
jonabtcJonathan Ocles
and
Jonathan Ocles
authored
Double factorial iterative (TheAlgorithms#4760)
* Adding the double factorial algorithm * Adding the double factorial algorithm Co-authored-by: Jonathan Ocles <[email protected]>
1 parent 01d5856 commit 4761fef

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

maths/double_factorial_iterative.py

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
def double_factorial(num: int) -> int:
2+
"""
3+
Compute double factorial using iterative method.
4+
5+
To learn about the theory behind this algorithm:
6+
https://en.wikipedia.org/wiki/Double_factorial
7+
8+
>>> import math
9+
>>> all(double_factorial(i) == math.prod(range(i, 0, -2)) for i in range(20))
10+
True
11+
>>> double_factorial(0.1)
12+
Traceback (most recent call last):
13+
...
14+
ValueError: double_factorial() only accepts integral values
15+
>>> double_factorial(-1)
16+
Traceback (most recent call last):
17+
...
18+
ValueError: double_factorial() not defined for negative values
19+
"""
20+
if not isinstance(num, int):
21+
raise ValueError("double_factorial() only accepts integral values")
22+
if num < 0:
23+
raise ValueError("double_factorial() not defined for negative values")
24+
value = 1
25+
for i in range(num, 0, -2):
26+
value *= i
27+
return value
28+
29+
30+
if __name__ == "__main__":
31+
import doctest
32+
33+
doctest.testmod()

0 commit comments

Comments
 (0)