python - 编写一个程序来计算级数的项之和

标签 python

编写一个程序来计算级数的项之和:4 - 8 + 12 - 16 + 20 - 24 + 28 - 32 + .... +/- n,其中 n 是输入。考虑 n 总是有效的(这 意味着它遵循系列模式)。

n = int(input("Enter n: "))
sum = 0
for i in range(4,n+4,4):
    sum += i - (i+2)
print("The sum of %s first terms is: %s"%(n,sum))

似乎找不到我遇到的问题

最佳答案

明确的公式怎么样?

def sumSeries(n):
  if n / 4 % 2 == 0:
    return - n / 2
  else:
    return (n + 4) / 2

该系列并没有做什么太有趣的事情,它只是不断地每两步添加+4,并且偶数步翻转标志:

4               = 4
4 - 8           = -4
4 - 8 + 12      = 8
4 - 8 + 12 - 16 = -8
...

一些例子:

for n in range(4, 100, 4):
  print("%d -> %d" % (n, sumSeries(n)))

输出:

4 -> 4
8 -> -4
12 -> 8
16 -> -8
20 -> 12
24 -> -12
28 -> 16
32 -> -16
36 -> 20
40 -> -20
44 -> 24
48 -> -24
52 -> 28
56 -> -28
60 -> 32
64 -> -32

关于python - 编写一个程序来计算级数的项之和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49460128/

相关文章:

python - 从 csv 文件中加载 url 列表,并针对相同的数据对它们进行逐一解析

python - 使用 Scikit-learn 计算信息增益

python - 使用 python 从虚拟机捕获实时网络流量

python - Airflow 外部任务传感器卡​​住

python - matplotlib 无法在 OS X 中运行,错误为 ' TKApplication is implemented in both'

Python 找不到 pyobdc。文件夹的名称可能是问题所在吗?

带有可变参数的 Python "maximum recursion depth exceeded in comparison"。但是,可以很好地处理列表

C++ 和 Python - 检查 PyObject 的类型失败

python - 使用另一个数组中的索引位置映射 Pandas 系列字符串

python - 一种确定字典值是否全部为空列表的方法