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

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

    I know this was 3 months ago but as an experiment because I am new to python I decided to try and combine some of the other people answers and I came up with a method you can pass the max number to and the divisors as a list and it returns the sum:

    def sum_of_divisors(below, divisors):
        return sum((n for n in xrange(below) if 0 in (n % d for d in divisors)))
    
    max = 1000
    nums = [3, 5]
    
    print sum_of_divisors(max, nums)
    

提交回复
热议问题