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

后端 未结 18 1003
萌比男神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:51

    There are floor(999/3) multiples of 3, floor(999/5) multiples of 5, and floor(999/15) multiples of 15 under 1000.

    For 3, these are: 3 + 6 + 9 + 12 +... + 999 = 3 * (1 + 2 + 3 + 4 +...+333)

    = 3 * (333 * 334 / 2) because the sum of the integers from 1 to k is k*(k+1)/2.

    Use the same logic for the sum of multiples of 5 and 15. This gives a constant time solution. Generalize this for arbitrary inputs.

提交回复
热议问题