Niet veel mensen weten het, maar Python biedt een directe functie die de faculteit van een getal kan berekenen zonder de hele code voor het berekenen van de faculteit te schrijven.
Naïeve methode om faculteit te berekenen
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)> |
>
>Uitvoer
The factorial of 23 is : 25852016738884976640000>
Tijdcomplexiteit: Op)
Hulpruimte: O(1)
Math.factorial() gebruiken
Deze methode is gedefinieerd in wiskunde module van Python. Omdat het een interne implementatie van het C-type heeft, is het snel.
Java-programmeerarrays
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> ))> |
>
>Uitvoer
The factorial of 23 is : 25852016738884976640000>
Tijdcomplexiteit: Op)
Hulpruimte: O(1)
Uitzonderingen in math.factorial()
- Als het gegeven getal negatief is:
Python3
# Uitzonderingen (niet-integraal nummer)
wiskunde importeren
print(De faculteit van 5.6 is : , end=)
# roept een uitzondering op
print(math.factorial(5.6))
>
>
Uitgang:
Traceback (most recent call last): File '/home/f29a45b132fac802d76b5817dfaeb137.py', line 9, in print (math.factorial(-5)) ValueError: factorial() not defined for negative values>
- Als het gegeven getal een niet-integrale waarde is:
Python3
>
>
Uitgang:
Traceback (most recent call last): File '/home/3987966b8ca9cbde2904ad47dfdec124.py', line 9, in print (math.factorial(5.6)) ValueError: factorial() only accepts integral values>