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

I like this the most:

def divisibles(below, *divisors):
    return (n for n in xrange(below) if 0 in (n % d for d in divisors))

print sum(divisibles(1000, 3, 5))

range(k,max) does not include max, so you're really checking up to and including 998 (while 999 is a multiple of 3). Use range(1,1000) instead.


The problem with your first solution is that it double-counts multiples of 15 (because they are multiples of both 3 and 5).

The problem with your second solution is that it doesn't count 999 (a multiple of 3). Just set max = 1000 to fix this.


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))))