How do you duplicate factorial in python?

I have been dealing with this issue for a long time. I managed to make one recursive factorial.

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

Double factorial For an even integer n, a double factor product is the product of all even natural numbers 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'm not going to do a double factorial. Any help?

+4
source share
11 answers
reduce(int.__mul__,range(n,0,-2))
+16
source

Isn't that the same as factorial with a different final condition and a different parameter for calling recursion?

def doublefactorial(n):
     if n <= 0:
         return 1
     else:
         return n * doublefactorial(n-2)

n , , n == 0. n , , n == -1.

+4
def doublefactorial(n):
     if n <= 0:
         return 1
     else:
         return n * doublefactorial(n-2)

.

+1
def double_fact(number):
    if number==0 or number==1:
        return 1
    else:
        return number*double_fact(number-2)

, .

+1

, (-1) !!= 1, (-3)!!= -1 ( ( -2, -4,...) +/- inf), ... - . , . -.

import scipy.special as sp
from numpy import pi

def dfact(x):
    n = (x + 1.)/2.
    return 2.**n * sp.gamma(n + 0.5)/(pi**(0.5))

!: D

+1

Python 3.8, prod math, , range(n, 0, -2) :

import math

math.prod(range(n, 0, -2))

, n = 0, 1.

+1
def doublefactorial(n):
     if n in (0, 1):
         return 1
     else:
         return n * doublefactorial(n-2)

.

0

, ,

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

reduce(lambda x,y: y*x, range(n,1,-2))

, :

x = n
for y in range(n-2, 1, -2):
    x*=y

, , ? , , , , , , , , .

0

:

dfact = lambda n: (n <= 0) or n * dfact(n-2)

, "" .

!!= (2 * k)!/(2 ** k * k!)

k = (n + 1)/2. n = 2k, , ,

!!= (2k)!!= 2 * k * k!.

, , , :

import math
fact = math.factorial
def dfact(n):
  if n % 2 == 1:
    k = (n+1)/2
    return fact(2*k) / (2**k * fact(k))
  else:
    return 2**k * fact(k)

Now this code is obviously not very efficient for large n, but it is very instructive. More importantly, since we are now dealing with standard factorials, this is a very good starting point for optimization when working with really large numbers. Once you can try to use logarithms or gamma functions to obtain approximate double factorials for large numbers.

0
source
x=1
a=1
y=int(input("x= "))
while a<=y:
    x*=a
    a+=1
    if a==y+1:
        x1=1
        a1=1
        while a1<=x:
            x1*=a1
            a1+=1
print("x!! =",x1)

this

0
source

Source: https://habr.com/ru/post/1786489/


All Articles