实际上这个问题可以在O(1)而不是O(N)中解决而不使用任何循环或列表:
所需的总和是3的所有倍数加上所有5的倍数之和减去给定数字1000(LIMIT = 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