Least Common Multiple

Yesterday, while sitting around having nothing to do, I saw a tweet mentioning the smallest number divisible by 1-10 is 2,520 (Mathematically, it’s called Least Common Multiple - LCM). Since I have nothing to do, I think I’ll try to write some code.

I actually did this once but that was a long time ago. I tried it several ways and this one is the fastest.

require 'prime'

running = 1
finished = false

n = 20 # max number in range

prime_in_range = (1..n).to_a.keep_if(&:prime?)

until finished
  if prime_in_range.take_while { |p| running % p == 0 }.length == prime_in_range.length

    if (1..n).to_a.take_while { |i| running % i == 0 }.length == n
      finished = true
      break
    end

  end

  running += 1
end

p running

Messy as it is, it works. (Side note: the code shows how long I’ve been away from writing.) Anyway, I look around after I’m happy with the code and I found this …

n = 20 # max number in range

p (1..n).reduce(&:lcm)

That’s it. One line. Functional. Whatever you want to call it. And it blew my code away. Haha. That was fun.

Addition:

I go back and look for it. Last time I did this was 3 years ago, Project Euler #5