如何在一个范围内添加数字 [英] How to add numbers in a range

查看:70
本文介绍了如何在一个范围内添加数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,所以我正在尝试将 1000 以内 3 或 5 的倍数的每个数字相加,当我输入此代码时:

Hey so I'm trying to do a challenge to add every number in multiples of 3 or 5 under 1000, and when I put in this code:

for x in xrange(1000):
if x % 3 == 0 or x % 5 == 0:
    place = list([x])
    sum(place)

它只是列出了 3 和 5 的倍数的所有数字,有什么办法可以将它列出的所有数字相加吗?

it just lists all the numbers that are multiples of 3 and 5, is there any way I can add all the numbers that it lists?

推荐答案

您的问题是您没有在循环的每次迭代中保留任何值.您的循环将通过以下方式修复:

Your issue is you are not retaining any value through each iteration of your loop. Your loop would be fixed with:

place = []
for x in range(1000):
    if x % 3 == 0 or x % 5 == 0:
        place.append(x)
sum(place)

或者只是沿途计算:

result = 0
for x in range(1000):
    if x % 3 == 0 or x % 5 == 0:
        result += x
result

正如所指出的,一个简单的生成器表达式可以解决这个问题:

As pointed out, a simple generator expression would solve the problem:

sum(x for x in range(1000) if x % 3 == 0 or x % 5 == 0)

注意:我使用 Py3 - 在 Py2 中 xrange() 将通过避免 range()list 构造来优化.

Note: I use Py3 - in Py2 xrange() would be an optimisation by avoiding the list construction of range().

但是sum(range(n+1))有一个封闭形式:

s(n) = n * (n + 1) // 2

例如:

sum([0, 1, 2, 3, ..., 999]) == 999 * 1000 // 2 == 499500

可以扩展为 sum(range(0, n+1, c)) 为:

s(n, c) = c * (n//c) * (n//c + 1) // 2

例如:

sum([0, 3, 6, 9, ..., 999]) == 3 * (999//3) * (999//3 + 1) // 2 == 166833

所以你可以把问题改写为s(999, 3) + s(999, 5) - s(999, 15),你必须减去s(999, 15) 或者您重复计算所有可以被 35 整除的值,例如:

So you can rewrite the problem as s(999, 3) + s(999, 5) - s(999, 15), you must subtract s(999, 15) or you double count all the values that are divisible by both 3 and 5, e.g.:

In []:
n = 1000
s = lambda n, c: c  * (n//c) * (n//c + 1) // 2
s(n-1, 3) + s(n-1, 5) - s(n-1, 15)

Out[]:
233168

对于所有提出的各种 sum 方法,这是 O(1)O(n).

This is O(1) vs O(n) for all the various sum approaches proposed.

这篇关于如何在一个范围内添加数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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