Subscribe to A Tour Through Project Euler        RSS Feed
-----

Problem 1 - The Beginning.

Icon 1 Comments
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!

Thanks for reading.

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

November 2018

S M T W T F S
    123
45678910
11121314151617
18192021 22 2324
252627282930 

Tags

    Recent Entries

    Recent Comments

    Search My Blog

    0 user(s) viewing

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

    Categories