Python中的阶乘()

没有多少人知道,但python提供了一个直接函数,可以计算数字的阶乘,而无需编写计算阶乘的全部代码。

null

计算阶乘的朴素方法

# 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

使用数学。阶乘()

此方法定义于“ 数学 “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

数学上的例外。阶乘()

  • 如果给定数字为负数:

    # 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
    

本文由 曼吉星 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。

如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞5 分享