如何在Python中找到1000以下的3或5的所有倍数的和? [英] How to find the sum of all the multiples of 3 or 5 below 1000 in Python?

查看:461
本文介绍了如何在Python中找到1000以下的3或5的所有倍数的和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不确定是否应该将其发布在math.stackexchange上,但是它包含更多的编程功能,因此我将其发布在这里。

Not sure if I should've posted this on math.stackexchange instead, but it includes more programming so I posted it here.

这个问题似乎很简单,但我现在已经在这里坐了至少一个小时了,还没弄清楚。我尝试了不同的解决方案,并为其阅读了数学公式,但是在编写代码时,它给我的答案不正确!我为此提出了两种不同的解决方案,都给了我错误的答案。第一个解决方案给我265334,而第二个解决方案给我232169。答案是233168,所以第二个解决方案更接近。

The question seems really simple, but I've sat here for at least one hour now not figuring it out. I've tried different solutions, and read math formulas for it etc but it won't gives me the right answer when coding it! I made two different solutions for it, which both gives me the wrong answer. The first solution gives me 265334 while the second one gives me 232169. The answer is 233168, so the second solution is closer.

我要提到的是来自< a href = http://projecteuler.net/index.php?section=problems&id=1 rel = noreferrer>欧拉计画,确切地说是第一个。

这是我的代码。任何想法有什么问题吗?

Here's my code. Any ideas what's wrong?

nums = [3, 5]
max = 999

result = 0
for num in nums:
    for i in range(1,max):
        if num*i < max:
            result += num*i
print result


result = 0
for i in range(0,max):
    if i%3 == 0 or i%5 == 0:
        result += i

print result


推荐答案

range(k,max)不包括 max ,因此您实际上要检查并包括998(而999是3的倍数)。使用 range(1,1000)代替。

range(k,max) does not include max, so you're really checking up to and including 998 (while 999 is a multiple of 3). Use range(1,1000) instead.

这篇关于如何在Python中找到1000以下的3或5的所有倍数的和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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