RubyFlow The Ruby and Rails community linklog

×

The Ruby and Rails community linklog

Made a library? Written a blog post? Found a useful tutorial? Share it with the Ruby community here or just enjoy what everyone else has found!

Solving Project Euler Problem #1 in Ruby

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 100. Solution.

Comments

Thanks Pius, Here is another one liner : puts (1…1000).select { |n| n % 3 == 0 or n % 5 == 0 }.inject { |sum, n| sum + n } However, I prefer more of a arithmetical approach.

By the way reason I like the mathematical approach is, it saves so many checks like , for all the numbers we are checking the divisibility by either 3 or 5. The older approach saves it, and should be more efficient asymptotically, as the range increases.

Post a comment

You can use basic HTML markup (e.g. <a>) or Markdown.

As you are not logged in, you will be
directed via GitHub to signup or sign in