首页 > 解决方案 > 使用 Python 对 1000 以下的 3 和 5 的倍数求和

问题描述

我编写了一个程序,旨在找到 1000 以下的所有 3 和 5 的倍数之和。我得到的输出是266333,但这不是正确的答案。请帮忙,这是我的代码:

x = 3
y = 5
x_list = []
y_list = []

while x < 1000:
    x_list.append(x)
    x += 3

while y < 1000:
    y_list.append(y)
    y += 5

numsum = sum(x_list + y_list)
print(numsum)

标签: pythonlistwhile-loopsumset

解决方案


The issue here is that you're adding all of the numbers which are multiples of 3 and all of the numbers that are multiples of 5, which includes the numbers that are multiples of both (e.g. 15, 30, 45, etc.) twice.

To simplify, let's look at the same problem, but with the multiples of 3 & 5 below 20.
After modifying the while loops to while x < 20 & while y < 20 respectively, we would end up with these two lists:

x_list = [3, 6, 9, 12, 15, 18]
y_list = [5, 10, 15]

The current code sum(x_list + y_list) equates to sum([3, 6, 9, 12, 15, 18, 5, 10, 15]), which gives us 93, but if you look closely, this includes 15 twice because it's a multiple of both 3 & 15, which we don't want.

What we want to do here, is to remove all duplicates from the x_list + y_list list, however there's no need to iterate through the lists and remove duplicates, because Python has a data type designed for this called a set. A set is defined in the Python documentation as "Unordered collections of unique elements", and while it may not store the order of elements within it (which can make a difference in some situations), we're just trying to not have duplicates so we can get the right sum, so we don't care what order they're in.

Continuing the simplified example, set(x_list + y_list) equates to sum({3, 5, 6, 9, 10, 12, 15, 18}) which you may notice only includes 15 once, and gives us 78, which is 15 less than 93.

Therefore, your second to last line should instead read numsum = sum(set(x_list + y_list)), which in the original situation (summing multiples of 3 & 5 below 1000) will give you 233168. Counting all those duplicates caused the calculation to be off by 33165.

Note: While I found this solution independently, it had previously been mentioned in the comments by Prune


推荐阅读