Lazy Evaluation

Marina's coding (mis)adventures

May 2008 - Posts

euler problem #5

 What is the smallest number that is evenly divisible by all of the numbers from 1 to 20?

----

To solve this problem easily, we need to remember that the smallest number that is evenly divisible by two numbers is their least common multiple.  Armed with this knowledge (and the fact that ruby already has a least common multiple function!), we can write:

numbers=(1..20).to_a
puts numbers.inject{ |x,n| x.lcm(n) }

 

So for those of you at SRT (or elsewhere) that still harbor any doubts about ruby, can you beat that?!  Fine, ok, so you might say that using a built-in lcm function is kind of lame.  So as a bonus, here's how I implemented lcm myself in a cute way using the greatest common divisor:

def gcd(a,b)
  if b==0 : a
  else
    gcd(b, a % b )
  end
end

def lcm(a,b)
  (a*b)/gcd(a,b)
end

 

 

Posted Thursday, May 01, 2008 9:40 PM by mfedner | with no comments

Filed under: ,