【每日一题】2021.10.20
F(n)=1!+2!+3!+...+n!, 编程求F(50), F(100), F(1000)的值(n! 表示阶乘运算)
编程语言:包括但不限于Python
先说阶乘函数的递归法:
def F(n):
if n==1: return 1
return n*F(n-1)
可以用三元表达式合并成一行:
def F(n):
return 1 if n==1 else n*F(n-1)
用逻辑运算改写三元表达式:
def fact(n):
return n==1 or 1 and n*fact(n-1)
上式当n=1时,输出True;用强制转换改造一下:
def fact(n):
return int(n==1) or 1 and n*fact(n-1)
递归的缺点,递归层数多到一定程度会报错:RecursionError: maximum recursion depth exceeded in comparison
用循环递推就没有这个缺点:
def fact(n):
res = 1
for i in range(1,n+1):
res *= i
return res
标准库math中有现成的函数,导入就能用:
from math import factorial as fact
回到正题:求F(n)=1!+2!+3!+...+n!
def func(n):
from math import factorial as fact
res = 0
for i in range(1,n+1):
res += fact(i)
return res
扩展:不使用阶乘函数也能求本题,把公式变形一下:
F(n)=1*(1+2*(1+3*(1+...(n-1)(1+n)))),n=4时即:
1!+2!+3!+4!
= 1+1x2+1x2x3 + 1x2x3x4
= 1+1x(2+2x3 + 2x3x4 )
= 1+1x(2x(1+3 + 3x4 ))
= 1x(1+1x(2x(1+3x(1 + 4 ))))
这样就用一个循环就能解决:
def SumofFact(n):
res = n
for i in range(n-1,0,-1):
res = i*(1+res)
return res
>>> SumofFact(50)
31035053229546199656252032972759319953190362094566672920420940313
>>> SumofFact(50)==func(50)
True
>>> #用库函数定义的func(n)验证无误
更多题目,请到CSDN社区“派森特给站”! https://bbs.csdn.net/forums/PythonTogether?typeId=18060