阶乘指从1乘以2乘以3乘以4,一直到所求数
表达阶乘是,用“!”表示,例如s得阶乘是s!
求1!+2!+3!+4!+。。。+20!
一般计算
1 n = int(input("输入数:")) 2 factorial,sum1 = 1,0 3 4 for i in range(1,n+1): 5 factorial *= i 6 sum1 += factorial 7 8 print(sum1)
执行结果:
输入数:20 2561327494111820313
用递归来计算:
1 def factorial(n): 2 if n == 1: 3 return 1 4 if n == 2: 5 return 2 6 else: 7 return factorial(n-1)*n 8 if __name__ == '__main__': 9 from functools import reduce 10 n = int(input("输入数:")) 11 list1 = [] 12 sum1 = 0 13 for i in range(1,n+1): 14 list1.append(factorial(i)) 15 print(list1) 16 print(reduce(lambda x,y:x+y,list1)) 17
执行结果:
输入数:20 [1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800, 479001600, 6227020800, 87178291200, 1307674368000, 20922789888000, 355687428096000, 6402373705728000, 121645100408832000, 2432902008176640000] 2561327494111820313