Skip to content
scipython.com

P2.4.6The double factorial function

The factorial function, \(n! = 1\cdot 2\cdot 3\cdot \cdots (n-1)n\) is the product of the first \(n\) positive integers and is provided by the math module's factorial method. The double factorial function, \(n!!\), is the product of the positive odd integers up to and including \(n\) (which must itself be odd):

\[n!! = \prod_{i=1}^{(n+1)/2} (2i-1) = 1\cdot 3\cdot 5\cdots (n-2) \cdot n.\]

Write a routine to calculate \(n!!\) in Python.

As a bonus exercise, extend the formula for to allow for even \(n\) as follows:

\[n!! = \prod_{i=1}^{n/2} (2i) = 2\cdot 4\cdot 6\cdots (n-2)\cdot n.\]
Show solution

To calculate \(n!!\) for odd \(n\), simply loop over the odd integers up to and including \(n\), multiplying them together:

# Calcualate n!! = 1.3.5.7...(n-2)n for odd n
n = 11
dfactorial = 1
for i in range(3, n+1, 2):
    dfactorial *= i
print('{:d}!! = {:d}'.format(n, dfactorial))

For even \(n\), note that

\[n!! = \prod_{i=1}^{n/2} (2i) = 2^{n/2} (n/2)!,\]

so:

# Calcualate n!! = 2.4.6.8...(n-2)n for even n
import math
n = 10
dfactorial = 2**(n // 2) * math.factorial(n // 2)
print('{:d}!! = {:d}'.format(n, dfactorial))