Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you a double factorial in python?

I've been stucked on this question for a really long time. I've managed to do a single recursive factorial.

def factorial(n):
     if n == 0:
         return 1
     else:
         return n * factorial(n-1)

Double factorial For an even integer n, the double factorial is the product of all even positive integers less than or equal to n. For an odd integer p, the double factorial is the product of all odd positive integers less than or equal to p.

If n is even, then n!! = n*(n - 2)*(n - 4)*(n - 6)* ... *4*2

If p is odd, then p!! = p*(p - 2)*(p - 4)*(p - 6)* ... *3*1

But I have no idea to do a double factorial. Any help?

like image 602
python learner Avatar asked Jan 19 '11 20:01

python learner


People also ask

What is double factorial in Python?

Double factorial. This is the factorial with every second value skipped. E.g., 7!! = 7 * 5 * 3 * 1 . It can be approximated numerically as: n!! = special.gamma(n/2+1)*2**((m+1)/2)/sqrt(pi) n odd = 2**(n/2) * (n/2)! n even.

How do you write double factorial?

The double factorial, symbolized by two exclamation marks (!!), is a quantity defined for all integer s greater than or equal to -1. For an even integer n , the double factorial is the product of all even integers less than or equal to n but greater than or equal to 2.


1 Answers

from functools import reduce # only in Python 3

reduce(int.__mul__, range(n, 0, -2))
like image 158
Kabie Avatar answered Sep 22 '22 12:09

Kabie