File tree 1 file changed +33
-0
lines changed
1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change
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 ()
You can’t perform that action at this time.
0 commit comments