Least Common Multiple

tags: multiple loop element-include-check

Compute the least common multiple (LCM) of two integers.

Given m and n, the least common multiple is the smallest positive integer that has both m and n as factors.

Least Common Multiple is the smallest positive number that is a multiple of two or more numbers. Refer mathisfun site for a good explanation.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
def lcm(m, n)
  first = m
  second = n
  
  multiples_f = []
  multiples_s = []
  
  loop do    
    first = first + m
    multiples_f << first  

    second = second + n
    multiples_s << second

    if multiples_f.include?(second)
      return second
    end

    if multiples_s.include?(first)
      return first
    end
  end
end

p lcm(3,5)