Solution: Finding the LCM
Go over the implementation of finding the LCM and analyze ways to improve its performance.
We'll cover the following...
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
checkvariable, which is passed as an argument tostep...