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.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay