Problem 1 – Project Euler

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.

def solve_elur1
arr = []
1.upto(999) do |i|
arr << i if (i%3 == 0) || (i%5 == 0)
end
puts "there are #{arr.size} elements that be multiples of 3 or 5 below"
sum = 0
arr.inject(0) do |sum, j|
sum += j
end
puts "result of ElurProjects: the sum of all the multiples of 3 or 5 below 1000
is #{sum}"
end

17fav 收藏本文

One Response

  1. sum = 0
    (1...1000).each { |i| sum += i if i % 3 == 0 || i % 5 == 0 }
    puts "Sum of multiples of 3 and 5 smaller 1000: #{sum}"

Leave a Reply

Formatting: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">



收藏 & 分享

Powered by 17fav.com