|
| 1 | +def double_factorial_recursive(n: int) -> int: |
| 2 | + """ |
| 3 | + Compute double factorial using recursive method. |
| 4 | + Recursion can be costly for large numbers. |
| 5 | +
|
| 6 | + To learn about the theory behind this algorithm: |
| 7 | + https://en.wikipedia.org/wiki/Double_factorial |
| 8 | +
|
| 9 | + >>> from math import prod |
| 10 | + >>> all(double_factorial_recursive(i) == prod(range(i, 0, -2)) for i in range(20)) |
| 11 | + True |
| 12 | + >>> double_factorial_recursive(0.1) |
| 13 | + Traceback (most recent call last): |
| 14 | + ... |
| 15 | + ValueError: double_factorial_recursive() only accepts integral values |
| 16 | + >>> double_factorial_recursive(-1) |
| 17 | + Traceback (most recent call last): |
| 18 | + ... |
| 19 | + ValueError: double_factorial_recursive() not defined for negative values |
| 20 | + """ |
| 21 | + if not isinstance(n, int): |
| 22 | + raise ValueError("double_factorial_recursive() only accepts integral values") |
| 23 | + if n < 0: |
| 24 | + raise ValueError("double_factorial_recursive() not defined for negative values") |
| 25 | + return 1 if n <= 1 else n * double_factorial_recursive(n - 2) |
| 26 | + |
| 27 | + |
| 28 | +def double_factorial_iterative(num: int) -> int: |
| 29 | + """ |
| 30 | + Compute double factorial using iterative method. |
| 31 | +
|
| 32 | + To learn about the theory behind this algorithm: |
| 33 | + https://en.wikipedia.org/wiki/Double_factorial |
| 34 | +
|
| 35 | + >>> from math import prod |
| 36 | + >>> all(double_factorial_iterative(i) == prod(range(i, 0, -2)) for i in range(20)) |
| 37 | + True |
| 38 | + >>> double_factorial_iterative(0.1) |
| 39 | + Traceback (most recent call last): |
| 40 | + ... |
| 41 | + ValueError: double_factorial_iterative() only accepts integral values |
| 42 | + >>> double_factorial_iterative(-1) |
| 43 | + Traceback (most recent call last): |
| 44 | + ... |
| 45 | + ValueError: double_factorial_iterative() not defined for negative values |
| 46 | + """ |
| 47 | + if not isinstance(num, int): |
| 48 | + raise ValueError("double_factorial_iterative() only accepts integral values") |
| 49 | + if num < 0: |
| 50 | + raise ValueError("double_factorial_iterative() not defined for negative values") |
| 51 | + value = 1 |
| 52 | + for i in range(num, 0, -2): |
| 53 | + value *= i |
| 54 | + return value |
| 55 | + |
| 56 | + |
| 57 | +if __name__ == "__main__": |
| 58 | + import doctest |
| 59 | + |
| 60 | + doctest.testmod() |
0 commit comments