Pythonのfactorial()

あまり知られていませんが、Python には、階乗を計算するためのコード全体を書かなくても、数値の階乗を計算できる直接関数が用意されています。

階乗を計算する単純な方法

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

出力

The factorial of 23 is : 25852016738884976640000 

時間計算量: の上)
補助スペース: ○(1)

math.factorial() の使用

このメソッドは次のように定義されています 数学 Pythonのモジュール。 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> ))>

出力

The factorial of 23 is : 25852016738884976640000 

時間計算量: の上)
補助スペース: ○(1)

math.factorial() の例外

    指定された数値が負の場合:

Python3




# math.factorial() を示す Python コード
# 例外 (非整数)

数学をインポートする

print(5.6 の階乗は : , end=)

# 例外が発生します
print(math.factorial(5.6))

出力:

Traceback (most recent call last): File '/home/f29a45b132fac802d76b5817dfaeb137.py', line 9, in print (math.factorial(-5)) ValueError: factorial() not defined for negative values 
    指定された数値が非整数値の場合:

Python3




出力:

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