faktoriāls () Python valodā

Ne daudzi cilvēki zina, taču python piedāvā tiešu funkciju, kas var aprēķināt skaitļa faktoriālu, neierakstot visu faktoriāla aprēķināšanas kodu.

Naiva metode faktoriāla aprēķināšanai

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

Izvade

The factorial of 23 is : 25852016738884976640000 

Laika sarežģītība: O(n)
Palīgtelpa: O(1)

Izmantojot math.factorial()

Šī metode ir definēta matemātika python modulis. Tā kā tam ir C tipa iekšējā ieviešana, tas ir ātrs.

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

Izvade

The factorial of 23 is : 25852016738884976640000 

Laika sarežģītība: O(n)
Palīgtelpa: O(1)

Izņēmumi math.factorial()

    Ja norādītais skaitlis ir negatīvs:

Python3




# Python kods, lai parādītu math.factorial()
# Izņēmumi (neintegrālais numurs)

importēt matemātiku

drukāt (5.6 faktoriāls ir : , end=)

# rada izņēmumu
drukāt (math.factorial(5.6))

Izvade:

Traceback (most recent call last): File '/home/f29a45b132fac802d76b5817dfaeb137.py', line 9, in print (math.factorial(-5)) ValueError: factorial() not defined for negative values 
    Ja norādītais skaitlis ir neintegrālā vērtība:

Python3




Izvade:

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