logo

faktorial() in Python

Nicht viele Leute wissen es, aber Python bietet eine direkte Funktion, die die Fakultät einer Zahl berechnen kann, ohne den gesamten Code zur Berechnung der Fakultät schreiben zu müssen.

Naive Methode zur Berechnung der Fakultät



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)>



>

>

Ausgabe

The factorial of 23 is : 25852016738884976640000>

Zeitkomplexität: An)
Hilfsraum: O(1)

Verwendung von math.factorial()

Diese Methode ist in definiert Mathematik Modul von Python. Da es über eine interne Implementierung vom Typ C verfügt, ist es schnell.

Schaltfläche im mittleren CSS
 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>))>

>

>

Ausgabe

The factorial of 23 is : 25852016738884976640000>

Zeitkomplexität: An)
Hilfsraum: O(1)

Ausnahmen in math.factorial()

    Wenn die angegebene Zahl negativ ist:

Python3




# Python-Code zur Demonstration von math.factorial()
# Ausnahmen (nicht ganzzahlige Zahl)

Mathematik importieren

print(Die Fakultät von 5.6 ist: , end=)

# löst eine Ausnahme aus
print(math.factorial(5.6))

>

>

Ausgabe:

Traceback (most recent call last): File '/home/f29a45b132fac802d76b5817dfaeb137.py', line 9, in print (math.factorial(-5)) ValueError: factorial() not defined for negative values>
    Wenn die angegebene Zahl ein nicht ganzzahliger Wert ist:

Python3




>

>

Ausgabe:

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