1000以下3或5的所有倍数之和

2024-09-22 14:28:07 发布

您现在位置:Python中文网/ 问答频道 /正文

初学者-尝试制作一个简单的python程序来计算/回答这个问题:

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below 1000.

目前我有:

a = 0
b = 0
while a < 1000:
    a = a + 3
    print (a)

while b < 1000
    b = b + 5
    print (b)

这将打印所有正在考虑的数字。我只需要把它们加在一起,这就是我的答案。

我希望发生以下两件事之一,而不是我编写的代码:

  1. 我希望所有这些都发生在内部,因此不必使用“打印”功能。只需打印所有倍数的总和。
  2. 我想把所有这些东西都打印出来,但我也想把它们的总和也打印出来。有没有办法让电脑把它打印出来的每一件东西的价值都计算出来?

Tags: orofthe程序ifalllistbelow
3条回答

我将使用一个for循环来迭代所选range中的每个数字。然后,您可以检查模%是否等于0,这意味着除以这些值时它没有余数,如果是,则将其添加到总数中。

total = 0
for num in range(1000):
    if num % 3 == 0 or num % 5 == 0:
        print(num)
        total += num

>>> total
233168

在Python中,可以使用生成器表达式在一行中完成此操作:

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

range(1000)生成从0到999(含)的所有整数。对于这些整数中的每一个,如果它可被3整除或可被5整除,则它包含在结果中。sum(...)函数将所有这些数字相加,最后print(...)打印结果。

实际上,这个问题可以用O(1)而不是O(N)来解决,而无需使用任何循环或列表:

所需的和是3的所有倍数之和加上5的所有倍数之和减去给定数字1000(极限=999)以下(3*5=15)的倍数之和。这些和被计算为算术级数的和。 其计算方法如下:

LIMIT=999

# Get the upper bounds for the arithmetic series
upper_for_three = LIMIT // 3
upper_for_five = LIMIT // 5
upper_for_fifteen = LIMIT // 15

# calculate sums
sum_three = 3*upper_for_three*(1 + upper_for_three) / 2
sum_five = 5*upper_for_five*(1 + upper_for_five) / 2
sum_fifteen = 15*upper_for_fifteen*(1 + upper_for_fifteen) / 2

# calculate total
total = sum_three + sum_five - sum_fifteen

# print result with Python 3
print(int(total))

结果是:

>>> 
233168

相关问题 更多 >