No molta gent ho sap, però python ofereix una funció directa que pot calcular el factorial d'un nombre sense escriure tot el codi per calcular el factorial.
Mètode ingenu per calcular factorials
Python 3
# 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)> |
>
>Sortida
The factorial of 23 is : 25852016738884976640000>
Complexitat temporal: O(n)
Espai auxiliar: O(1)
Utilitzant math.factorial()
Aquest mètode es defineix a matemàtiques mòdul de Python. Com que té una implementació interna de tipus C, és ràpid.
javascript més proper
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.>
Python 3
# Python code to demonstrate math.factorial()> import> math> print> (> 'The factorial of 23 is : '> , end> => '')> print> (math.factorial(> 23> ))> |
>
>Sortida
The factorial of 23 is : 25852016738884976640000>
Complexitat temporal: O(n)
Espai auxiliar: O(1)
Excepcions a math.factorial()
- Si el número donat és negatiu:
Python 3
# Excepcions (número no integral)
importar matemàtiques
print(El factorial de 5.6 és: , final=)
# planteja una excepció
imprimir(matemàtiques.factorial(5.6))
>
>
Sortida:
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 nombre donat és un valor no integral:
Python 3
>
>
Sortida:
Traceback (most recent call last): File '/home/3987966b8ca9cbde2904ad47dfdec124.py', line 9, in print (math.factorial(5.6)) ValueError: factorial() only accepts integral values>