在python中从1到n,2到n,... n的总和 [英] Sum from 1 to n, 2 to n, ... n in python

查看:74
本文介绍了在python中从1到n,2到n,... n的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图得到一系列从 1 到 n、2 到 n、... 和 n 的总和

I was trying to get a series of sum from 1 to n, 2 to n, ..., and n

例如,如果n=5,那么结果应该是15141295

For example, if n=5, then the result should be 15 14 12 9 5

请评论下面的代码.我不知道出了什么问题.

Please comment for the code below. I can't figure out what's wrong.

n=int(input())
sum=0
m=0
factorial=1

for i in range(1, n + 1):
    factorial *= i
    sum=factorial-m
    print(sum)

推荐答案

一种相当简单的方法:

n = 5
s = sum(range(n+1))
for i in range(n):
    s -= i
    print(s)

15
14
12
9
5

这篇关于在python中从1到n,2到n,... n的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆