Python-阶乘和 [英] Python - Sum of the factorials
本文介绍了Python-阶乘和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
B=0
A=1
m=int(input("input a number please "))
for k in range (1,m+1) :
for i in range (1,k+1) :
A=i*A
B=B+A
print("this is your number",B)
如果我输入4,这给我418,应该给我32,我在这里做错了什么?
if i type 4 ,this gives me 418 , it's supposed to give me 32, what am i doing wrong here?
我已经尝试了所有方法来纠正它
I've tried everything to correct it
编辑:计算阶乘的和,如果我输入4,它将计算1! + 2! + 3! + 4!
Edit : this to calculate the sum of factorials , if i type 4 it will calculate 1! + 2! + 3! + 4!
推荐答案
解决方案1
您可以使用:
math.factorial(x)
用 0
初始化一个和,使用for循环并将上述行的结果添加到和中:
Initialize a sum with 0
, use a for loop and add the result of the above line to the sum:
from math import factorial
s=0
m=4
for k in range (1,m+1) :
s=s+factorial(k)
print (s)
解决方案2
手动:
s=0
m=4
for i in range(1,m+1):
p=1
for k in range(1,i+1):
p*=k
s+=p
print (s)
这篇关于Python-阶乘和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文