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.

mult3 = [] #multiples of 3 mult5 = [] #multiples of 5 for i in range(1000): if i % 3 == 0 and i % 5 != 0: #make sure its numbers are divisible by 3 but not 5 mult3.append(i) if i % 5 == 0 and i % 3 != 0: #make sure its numbers are divisible by 5 but not 3 mult5.append(i) total3 = sum(mult3) #sum of all elements in mult3 total5 = sum(mult5) #sum of all elements in mult5 print(total3 + total5)

I was wrong with the answer of 200003.
Had I misunderstood the question or are there any bugs in my code?

Link to the original question

## Answer

You can take the iterative approach: O(n)

s35 = sum(n for n in range(1000) if n%3 == 0 or n%5 == 0)

Or you can compute it mathematically: O(1)

n3 = (1000-1)//3 # number of multiples of 3 (includes multiples of 15) n5 = (1000-1)//5 # number of multiples of 5 (includes multiples of 15) n15 = (1000-1)//15 # number of multiples of 15 (counted twice) s35 = n3*(n3+1)//2*3 + n5*(n5+1)//2*5 - n15*(n15+1)//2*15