Tuesday, September 18, 2007

Project Euler

My solution to Problem #1 from Project Euler (and, I should point out, my first functioning Ruby program). They liked my answer.



# Project Euler, Problem #1
# Compute the sum of all natural numbers below 1000
# that are multiples of 3 or 5
#
# The problem gives no specific instructions about
# numbers that are multiples of both, like 15, but
# apparently they want us to count those once. The
# code below counts them as multiples of 3, and the
# answer matches with what they want.

numbers = 3..999
sum = 0

numbers.each do |number|
# Is it a multiple of 3?
# If so, add to the total
if number % 3 == 0
sum = sum + number
# Otherwise, is it a multiple of 5?
elsif number % 5 == 0
sum = sum + number
end
end

puts "The sum is: " + sum.to_s

No comments: