Search⌘ K
AI Features

Solution: LCM of Multiple Numbers Using a Method

Understand how to create and use methods in Ruby to calculate the least common multiple (LCM) of multiple numbers. This lesson demonstrates defining reusable functions and applying loops to solve the problem incrementally.

We'll cover the following...

Solution

Ruby
def lcm(a, b)
(a..a*b).each do |n|
if n % a == 0 && n % b == 0
return n
end # end of if
end # end of loop
end # end of method
m = 1
(2..15).each do |w|
m = lcm(m, w)
end
puts "The lowest number that is dividable by 1 to 15 is: #{m}"

Explanation

  • Lines 1–7: We define a method named lcm with two ...