初学者-尝试制作一个简单的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)
这将打印所有正在考虑的数字。我只需要把它们加在一起,这就是我的答案。
我希望发生以下两件事之一,而不是我编写的代码:
我将使用一个
for
循环来迭代所选range
中的每个数字。然后,您可以检查模%
是否等于0,这意味着除以这些值时它没有余数,如果是,则将其添加到总数中。在Python中,可以使用生成器表达式在一行中完成此操作:
range(1000)
生成从0到999(含)的所有整数。对于这些整数中的每一个,如果它可被3整除或可被5整除,则它包含在结果中。sum(...)
函数将所有这些数字相加,最后print(...)
打印结果。实际上,这个问题可以用O(1)而不是O(N)来解决,而无需使用任何循环或列表:
所需的和是3的所有倍数之和加上5的所有倍数之和减去给定数字1000(极限=999)以下(3*5=15)的倍数之和。这些和被计算为算术级数的和。 其计算方法如下:
结果是:
相关问题 更多 >
编程相关推荐