Sat30Jan

  1. Project Euler in Ruby: Problem #1

    What is Project Euler?

    Project Euler is a series of challenging mathematical/computer programming problems that will require more than just mathematical insights to solve. Although mathematics will help you arrive at elegant and efficient methods, the use of a computer and programming skills will be required to solve most problems.

    The motivation for starting Project Euler, and its continuation, is to provide a platform for the inquiring mind to delve into unfamiliar areas and learn new concepts in a fun and recreational context.

    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.

    irb(main):001:0> (0..999).select { |i| i % 3 == 0 || i % 5 == 0 }.reduce :+
    => 233168

    Bada-bing, bada-boom

    Explanation

    (0..999) is every a Range object containing every natural number under 1000. As it is an Enumerable object…

    irb(main):002:0> Range.included_modules
    => [Enumerable, Kernel]

    It responds to select. Select takes a block of code, and returns each element of the enumerable object in a new array when the block evaluates as true. Our block simply asks “is there no remainder when we divide this integer by 3 or 5?” So that is how we extract the numbers that are multiples of 3 or 5.

    Calling reduce :+ is equivalent to calling inject and adding the block variable to the memo block variable. That is how we find the sum of those numbers.