DEV Community

Mezbah Alam
Mezbah Alam

Posted on

Finding the LCM of an array of numbers in Ruby

This code demonstrates some common techniques in Ruby, such as defining methods, using recursion, and using the reduce method to iterate over an array and perform a computation on its elements. Many Ruby developers appreciate concise and efficient code like this, especially when it solves a common problem like finding the LCM of an array of numbers.

# A method that returns the greatest common divisor (GCD) of two numbers using the Euclidean algorithm
def gcd(a, b)
  return a if b == 0
  gcd(b, a % b)
end

# A method that returns the least common multiple (LCM) of two numbers using the GCD method above
def lcm(a, b)
  (a * b) / gcd(a, b)
end

# A method that uses the LCM method above to find the LCM of an array of numbers
# and adds a heartfelt message to the output
def lcm_of_array(array)
  lcm = array.reduce(1) { |lcm, n| lcm(lcm, n) }
  puts "The least common multiple of the numbers #{array} is #{lcm}. May it bring you joy and happiness."
  return lcm
end

# Example usage
lcm_of_array([2, 3, 4, 5]) # Output: "The least common multiple of the numbers [2, 3, 4, 5] is 60. May it bring you joy and happiness."

Enter fullscreen mode Exit fullscreen mode

This version of the code includes a heartfelt message in the output, wishing the user joy and happiness when they use the lcm_of_array method.

Top comments (0)