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.


In [1]:
def foo(n):
    total = 0
    for i in range(n):
        if i % 3 == 0 or i % 5 == 0:
            total += i
    return total

In [2]:
n = 1000
%timeit foo(n)
foo(n)


1000 loops, best of 3: 282 us per loop
Out[2]:
233168

In [3]:
def foo(n):
    total = 0
    for i in range(n):
        if i % 3 == 0:
            total += i
        if i % 5 == 0:
            total += i
    return total

In [4]:
n = 1000
%timeit foo(n)
foo(n)


1000 loops, best of 3: 319 us per loop
Out[4]:
266333

In [5]:
def foo(n):
    return sum(filter((lambda x: x % 3 == 0 or x % 5 == 0), range(n)))

In [6]:
n = 1000
%timeit foo(n)
foo(n)


1000 loops, best of 3: 384 us per loop
Out[6]:
233168