Problem 1: Multiples of 3 and 5

时间:2021-09-17 11:29:13

小白一枚,python解法,共同学习,一起进步。

Problem 1: Multiples of 3 and 5

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.

解题思路:

找出所有3和5的倍数,不超过最大数n,去重求和即可。

 l = []  # 存放3和5倍数的数
n = 1000 # 最大数
for i in range(1, n):
if 3*i >= n: # 如果大于最大数,终止
break
l.append(3*i)
for i in range(1, n):
if 5*i >= n:
break
l.append(5*i)
l = set(l) # 去重,譬如15 30之类的
print(sum(l))

%time %run ol001.py
233168
Wall time: 2 ms