Project Euler Problem 1

The first problem of Project Euler is pretty simple. It reads:

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.

Well, the naive way to solve this problem is simply to generate a list, and then to find the sum of its elements:


sum(filter(lambda x: x%3==0 or x%5==0, range(1,1000)))

and the answer is 233168.

Although I appreciate the elegance of functional programming (lambda function, filter, sum), mathematically the above code is not a good solution. The sum of all numbers that are either dividable by 3 or 5 in fact equals the sum of all numbers that ar dividable by 3, plus the sum of all numbers that are dividable by 5, minus the sum of all numbers that are dividable by 15, therefore


rg = range(1,1000)
sum(filter(lambda x: x%3==0, rg)) + sum(filter(lambda x: x%5==0, rg)) - sum(filter(lambda x: x%15==0, rg))

And again, the answer is 233168.

Advertisement

Tags: , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s


Follow

Get every new post delivered to your Inbox.