Project Euler - Smallest multiple (Ruby) My code is very slow to run, and I am trying to find a way to make it more efficient. I know there must be a better way than to write each modulo operation.

The goal of the script is to find the smallest possible number than can be divided by numbers 1 to 20 without a remainder.

def divide
  (2..Float::INFINITY).each do |x|
      if x % 2 == 0 &amp;&amp; x % 3 == 0 &amp;&amp; x % 4 == 0 &amp;&amp; x % 5 == 0 &amp;&amp; x % 6 == 0 &amp;&amp; x % 7 == 0 &amp;&amp; x % 8 == 0 &amp;&amp; x % 9 == 0 &amp;&amp; x % 10 == 0 &amp;&amp; x % 11 == 0 &amp;&amp; x % 12 == 0 &amp;&amp; x % 13 == 0 &amp;&amp; x % 14 == 0 &amp;&amp; x % 15 == 0 &amp;&amp; x % 16 == 0 &amp;&amp; x % 17 == 0 &amp;&amp; x % 18 == 0 &amp;&amp; x % 19 == 0 &amp;&amp; x % 20 == 0
        print x
        break
      end
  end
end

divide
Array provides lcm() which gives you the least common multiple of two numbers. You can apply this to an entire array by applying it to each result as you go through it. This is what reduce does.

puts (1..20).reduce{|m,n| m.lcm(n)}


or even shorter:

puts (1..20).reduce(:lcm)


Because most of the calculations are done in the ruby implementation (e.g. C for MRI), this will be fast.