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.Here's my solution, implemented in Haskell:
Find the sum of all the multiples of 3 or 5 below 1000.
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?
Ruby!
ReplyDeletey = 0
1000.times { |x| y += x if (x%3 == 0 or x%5 == 0) }
puts y
Version 2.0:
ReplyDeletesum$filter(\x->(x`mod`5==0)||(x`mod`3==0))[1..999]
CHANGELOG
-Smarter function usage
-Removed superfluous spaces
Oh, and character counts:
ReplyDeleteFirst attempt: 71
Second attempt: 50
Your score: 64
You win the first round, although I didn't know I was competing yet...
Nor did I!
ReplyDelete46. (Ruby)
y=0;1000.times{|x|(x%3==0||x%5==0)?y+=x:0};p y