factorial() en Python

No mucha gente lo sabe, pero Python ofrece una función directa que puede calcular el factorial de un número sin escribir el código completo para calcular el factorial.

Método ingenuo para calcular factorial.

Python3




# Python code to demonstrate naive method> # to compute factorial> n> => 23> fact> => 1> for> i> in> range> (> 1> , n> +> 1> ):> > fact> => fact> *> i> print> (> 'The factorial of 23 is : '> , end> => '')> print> (fact)>

Producción

The factorial of 23 is : 25852016738884976640000 

Complejidad del tiempo: En)
Espacio Auxiliar: O(1)

Usando math.factorial()

Este método está definido en matemáticas módulo de Python. Debido a que tiene implementación interna tipo C, es rápido.

 math.factorial(x) Parameters : x : The number whose factorial has to be computed. Return value : Returns the factorial of desired number. Exceptions :  Raises Value error if number is negative or non-integral. 

Python3




# Python code to demonstrate math.factorial()> import> math> print> (> 'The factorial of 23 is : '> , end> => '')> print> (math.factorial(> 23> ))>

Producción

The factorial of 23 is : 25852016738884976640000 

Complejidad del tiempo: En)
Espacio Auxiliar: O(1)

Excepciones en math.factorial()

    Si el número dado es negativo:

Python3




# Código Python para demostrar math.factorial()
# Excepciones (número no integral)

importar matematicas

print(El factorial de 5.6 es: , end=)

# genera una excepción
imprimir(matemáticas.factorial(5.6))

Producción:

Traceback (most recent call last): File '/home/f29a45b132fac802d76b5817dfaeb137.py', line 9, in print (math.factorial(-5)) ValueError: factorial() not defined for negative values 
    Si el número dado es un valor no integral:

Python3




Producción:

Traceback (most recent call last): File '/home/3987966b8ca9cbde2904ad47dfdec124.py', line 9, in print (math.factorial(5.6)) ValueError: factorial() only accepts integral values