Project Euler 001 – IronRuby

2 02 2011

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.

Solution

# Add all the natural numbers below one

# thousand that are multiples of 3 or 5.

 

# this is interesting

# I wasn’t sure how to create the arrays

# with a step so I just rejected the ones

# I didn’t want.  For small numbers this

# should work fine

threes = (01000).reject { |i| i % 3 != 0 }

fives = (01000).reject { |i| i % 5 != 0 }

fifteens = (01000).reject { |i| i % 15 != 0 }

 

answer = 0

threes.each { |i| answer += i }

fives.each { |i| answer += i }

fifteens.each { |i| answer -= i }

puts answer

 

Discussion

Remember, Ruby is brand new to me.  I wasn’t really sure how to create an array with a step so I used the “reject” feature.  It felt pretty natural.

If you have questions, leave a comment or find me on Twitter (@azzlsoft) or email (rich@azzlsoft.com).