How to find the sum of all the multiples of 3 or 5 below 1000 in Python?

后端 未结 18 1158
萌比男神i
萌比男神i 2020-12-29 12:10

Not sure if I should\'ve posted this on math.stackexchange instead, but it includes more programming so I posted it here.

The question seems really simple, but I\'ve

18条回答
  •  太阳男子
    2020-12-29 12:39

    You are overcomplicating things. You just need a list of numbers that are multiples of 3 or 5 which you can get easily with a list comprehension:

    >>> [i for i in range(1000) if i % 3 == 0 or i % 5 == 0]
    

    Then use sum to get the total:

    >>> sum([i for i in range(1000) if i % 3 == 0 or i % 5 == 0])
    <<< 233168
    

    Or even better use a generator expression instead:

    >>> sum(i for i in range(1000) if i % 3 == 0 or i % 5 == 0)
    

    Or even better better (courtesy Exelian):

    >>> sum(set(list(range(0, 1000, 3)) + list(range(0, 1000, 5))))
    

提交回复
热议问题