Project Euler Problem #1

October 15, 2009

Read the details of the problem here.

Summary

Add all the natural numbers below one thousand that are multiples of 3 or 5.

Solution

I guess I could have used summing of arithmetic progressions to work this out even by hand but would it have been as quick as writing this brute-force one-liner in Groovy?

def answer =
    (1..<1000).findAll { (it % 3 == 0) || (it % 5 == 0) }.sum()

This runs in around 0.44 secs which seems a bit slow given it’s not doing any heavy lifting but it’s well within the 15-20s that I’m allowing myself for these Project Euler jobs.

Conclusion

In this case, Groovy’s ranges, list selector and list aggregate functions make this a snap to write and to understand. I must admit to preferring the a..<b syntax for an exclusive range expression to Ruby’s open range a...b syntax where it’s too easy to miss the extra full-stop on reading.

Advertisements

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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: