基于Python求解1+(1+2)+(1+2+3)+...+(1+2+3+...+n)之和

n = eval(input("请输入n值:"))
sum = 0

'解法一,采用两重迭代'
for i in range(1 , n+1):
    for j in range(1 , i+1):
        sum += j
print("1+(1+2)+(1+2+3)+...+(1+2+3+...+n)求和为:" + str(sum))

'解法二,采用一重迭代'
for i in range(1,n+1):
    sum += i*(i+1)/2
print("1+(1+2)+(1+2+3)+...+(1+2+3+...+n)求和为:" + str(sum))

'解法三,数学公式求和'
sum = n*(n+1)*(n+2)/6
print("1+(1+2)+(1+2+3)+...+(1+2+3+...+n)求和为:" + str(sum))

你可能感兴趣的:(python)