【一起来刷题吧】2021.10.20 求阶乘数列的和

【每日一题】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社区“派森特给站”! icon-default.png?t=LA23https://bbs.csdn.net/forums/PythonTogether?typeId=18060

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值