📜  Python中的阶乘()

📅  最后修改于: 2022-05-13 01:55:41.417000             🧑  作者: Mango

Python中的阶乘()

知道的人不多,但是Python提供了一个直接函数,可以计算一个数的阶乘,而无需编写计算阶乘的整个代码。

计算阶乘的朴素方法

# 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

使用 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.
# 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

math.factorial() 中的异常

  • 如果给定数字为负数:
    # Python code to demonstrate math.factorial()
    # Exceptions ( negative number )
      
    import math
      
    print ("The factorial of -5 is : ",end="")
      
    # raises exception
    print (math.factorial(-5))
    

    输出 :

    The factorial of -5 is : 
    

    运行时错误:

    Traceback (most recent call last):
      File "/home/f29a45b132fac802d76b5817dfaeb137.py", line 9, in 
        print (math.factorial(-5))
    ValueError: factorial() not defined for negative values
    
  • 如果给定数字是非整数值:
    # Python code to demonstrate math.factorial()
    # Exceptions ( Non-Integral number )
      
    import math
      
    print ("The factorial of 5.6 is : ",end="")
      
    # raises exception
    print (math.factorial(5.6))
    

    输出 :

    The factorial of 5.6 is : 
    

    运行时错误:

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