MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / double_factorial_recursive

Function double_factorial_recursive

maths/double_factorial.py:1–25  ·  view source on GitHub ↗

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, -

(n: int)

Source from the content-addressed store, hash-verified

1def 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
28def double_factorial_iterative(num: int) -> int:

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected