????阶乘是数学术语,表示从1乘以2乘以3乘以4一直乘到所要求的数。具体来说,一个正整数的阶乘是所有小于及等于该数的正整数的积,并且0的阶乘为1。例如,4的阶乘就是1×2×3×4=24,6的阶乘就是1×2×3×…×6=720。在表达阶乘时,使用“!”来表示,例如4!表示4的阶乘。
????阶乘运算符号由基斯顿·卡曼(Christian Kramp)于1808年发明。自然数n的阶乘写作n!,也可以用递归方式定义:0!=1,n!=(n-1)!×n。
????本文列举Python
中4种计算阶乘的方式
def factorial(n):
result = 1
for i in range(1, n+1):
result *= i
return result
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n-1)
import math
def factorial(n):
return math.factorial(n)
from functools import reduce
import operator
def factorial(n):
if n==0:
return 1
return reduce(operator.mul, range(1, n+1))
# -*- coding: utf-8 -*-
from functools import reduce
import operator
import math
def factorial01(n):
result = 1
for i in range(1, n+1):
result *= i
return result
def factorial02(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial02(n-1)
def factorial03(n):
return math.factorial(n)
def factorial04(n):
if n==0:
return 1
return reduce(operator.mul, range(1, n+1))
if __name__ == "__main__":
iSum=0
for iIdx in range(11):
ifactorial = factorial01(iIdx)
print(r'算法01:{}的阶乘为{}'.format(iIdx, factorial01(iIdx)))
print(r'算法02:{}的阶乘为{}'.format(iIdx, factorial02(iIdx)))
print(r'算法03:{}的阶乘为{}'.format(iIdx, factorial03(iIdx)))
print(r'算法04:{}的阶乘为{}'.format(iIdx, factorial04(iIdx)))
iSum += ifactorial
print(r'从1到{}阶乘和为{}'.format(10, iSum))
# 从1到10阶乘和为4037914
may the odds be ever in your favor ~