Subscribe to A Tour Through Project Euler

## Problem 1 - The Beginning.

Multiples of 3 and 5
Problem 1

"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."

Though I am a C# developer by trade, I think python will give us the cleanest, most readable solution for this problem. Fastest? Maybe, maybe not - we can test that later :cowboy:

My initial solution to this problem was

```    sum = 0
for x in range(1000):
if x % 3 == 0:
sum += x
if x % 5 == 0:
sum += x

print(sum)

```

Pretty embarrassing, right? Oh well, we all make stupid mistakes sometimes (or all the time) :withstupid:
If you don't see the issue with the above code, let me explain. The question was "Find the sum of all the multiples of 3 or 5 below 1000." The above solution does that, sort of - but it counts some numbers twice, for example 15. 15 is a multiple of both 3 and 5. Code revision time:

```    sum = 0
for x in range(1000):
if x % 3 == 0 or x % 5 == 0:
sum += x
print(sum)

```

Perfect. It works! But... we did this in python for a reason. What's the point of using python if you don't even make the code pythonic? So, we can actually change this to be a pretty little one liner:

```    print(sum(i for i  in range(1000) if i % 3 == 0 or i % 5 == 0))

```

Aaaaaand I'm sure there is something even cooler, but I'm satisfied with this solution.

Put that in your interpreter, (make sure you understand the solution), then head over to Project Euler and save your answer for problem 1!

### 1 Comments On This Entry

Page 1 of 1

#### MentalFloss

20 November 2018 - 06:08 PM
```print(sum(set(range(0,1000,5))|set(range(0,1000,3))))
```

print (the sum of (the set containing values 0 to 999 in increments of 5) union with (the set containing values 0 to 999 in increments of 3)).
0
Page 1 of 1

### Trackbacks for this entry [ Trackback URL ]

There are no Trackbacks for this entry

S M T W T F S
1 2 345
6789101112
13141516171819
20212223242526
2728293031