DEV Community

Mezbah Alam
Mezbah Alam

Posted on

1

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.

Heroku

Amplify your impact where it matters most — building exceptional apps.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (0)

Image of Quadratic

Free AI chart generator

Upload data, describe your vision, and get Python-powered, AI-generated charts instantly.

Try Quadratic free

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay