Peu de gens le savent, mais python propose une fonction directe qui peut calculer la factorielle d'un nombre sans écrire tout le code pour le calcul de la factorielle.
Méthode naïve pour calculer factorielle
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)> |
>
>Sortir
The factorial of 23 is : 25852016738884976640000>
Complexité temporelle : Sur)
Espace auxiliaire : O(1)
Utiliser math.factorial()
Cette méthode est définie dans mathématiques module de python. Parce qu’il a une implémentation interne de type C, il est rapide.
pointeur de déréférencement c
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> ))> |
>
>Sortir
The factorial of 23 is : 25852016738884976640000>
Complexité temporelle : Sur)
Espace auxiliaire : O(1)
Exceptions dans math.factorial()
- Si le nombre donné est négatif :
Python3
# Exceptions (numéro non intégral)
importer des mathématiques
print(La factorielle de 5,6 est : , end=)
# déclenche une exception
imprimer(math.factorial(5.6))
>
>
Sortir:
Traceback (most recent call last): File '/home/f29a45b132fac802d76b5817dfaeb137.py', line 9, in print (math.factorial(-5)) ValueError: factorial() not defined for negative values>
- Si le nombre donné est une valeur non intégrale :
Python3
>
>
Sortir:
Traceback (most recent call last): File '/home/3987966b8ca9cbde2904ad47dfdec124.py', line 9, in print (math.factorial(5.6)) ValueError: factorial() only accepts integral values>