Solution: Finding the HCF by Using a Method
Explore how to create a Ruby method that calculates divisors to find the highest common factor (HCF) of two numbers. Understand refactoring to improve code clarity and efficiency. This lesson helps you practice reusable methods and troubleshooting array handling in Ruby.
We'll cover the following...
We'll cover the following...
Solution
def get_divisors(num)
array = []
(1..num).each do |x|
check = num % x
if check == 0
array << x
end
end
return array
end
puts "Enter first number: "
num1 = gets.chomp.to_i
divisors_list_1 = get_divisors(num1)
puts "Enter second number: "
num2 = gets.chomp.to_i
divisors_list_2 = get_divisors(num2)
d1sorted = divisors_list_1.sort.reverse
d1sorted.each do |elem|
if divisors_list_2.include?(elem)
puts "The HCF is #{elem}"
break
end
endFinding the HCF using method
Explanation
Lines 1–10: Defines a method named
get_divisors, which accepts a numbernumand returns an array containing a list of divisors ...