Subscribe to A Tour Through Project Euler        RSS Feed

Problem 1 - The Beginning.

Icon Leave Comment
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


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

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!

Thanks for reading.

0 Comments On This Entry


Trackbacks for this entry [ Trackback URL ]

There are no Trackbacks for this entry

July 2018

151617181920 21


    Recent Entries

    Search My Blog

    0 user(s) viewing

    0 Guests
    0 member(s)
    0 anonymous member(s)