Search⌘ K

Solution: Finding the LCM

Explore how to find the lowest common multiple (LCM) of two numbers using Ruby. Understand the importance of using correct logical operators and optimizing the search by starting from the larger number to improve efficiency.

We'll cover the following...

Solution

# Calculate LCM
puts "Enter the first number: "
num1 = gets.chomp.to_i
puts "Enter the second number:"
num2 = gets.chomp.to_i
if num1 > num2 
  check = num1
else
  check = num2 
end
start_time = Time.now
(check..num1 * num2).step(check) do |n|
  if n % num1 == 0 && n % num2 == 0
    puts "The LCM for #{num1} and #{num2} is #{n}"
    break 
  end
end
puts "Calculation took #{Time.now - start_time} seconds"
Calculating the LCM of two numbers

Explanation

  • Lines 6–10: We assign the bigger number to the check variable, which is passed as an argument to step ...