2.24.2011

Euler 001

The first Project Euler problem asks

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.
Here's my solution, implemented in Haskell:


foldr (+) 0 (filter (\x -> (x `mod` 5==0) || (x `mod`3 == 0)) [1..999])
Wow, that was easy, although it still seems like overkill. There's probably a way to avoid using both foldr and filter since I'm just working with numbers here.

I think to write an equivalent one-liner in Perl, I'd have to use structures originally borrowed from functional languages, which would kind of defeat the point. Maybe I should try to do it in terse Java?

4 comments:

  1. Ruby!

    y = 0
    1000.times { |x| y += x if (x%3 == 0 or x%5 == 0) }
    puts y

    ReplyDelete
  2. Version 2.0:

    sum$filter(\x->(x`mod`5==0)||(x`mod`3==0))[1..999]

    CHANGELOG
    -Smarter function usage
    -Removed superfluous spaces

    ReplyDelete
  3. Oh, and character counts:

    First attempt: 71
    Second attempt: 50

    Your score: 64

    You win the first round, although I didn't know I was competing yet...

    ReplyDelete
  4. Nor did I!

    46. (Ruby)

    y=0;1000.times{|x|(x%3==0||x%5==0)?y+=x:0};p y

    ReplyDelete