Search⌘ K

Solution: Finding the HCF

Understand the process of finding the highest common factor (HCF) between two numbers using Ruby. This lesson guides you through writing code that identifies divisors, sorts them for efficiency, and determines the HCF. You will learn to focus on the core problem-solving approach before adding extra code, enabling you to build clear and effective solutions.

We'll cover the following...

Solution

divisors_list_1 = [] 
divisors_list_2 = []
puts "Enter first number: " 
num1 = gets.chomp.to_i 
(1..num1).each do |x|
    check = num1 % x 
    if check == 0
        divisors_list_1 << x 
    end
end
puts "Enter second number: " 
num2 = gets.chomp.to_i 
(1..num2).each do |x|
    check = num2 % x
    divisors_list_2 << x if check == 0        
end
d1sorted = divisors_list_1.sort.reverse 
d1sorted.each do |elem|
    if divisors_list_2.include?(elem) 
        puts "The HCF is #{elem}" 
        break
    end
end
Calculating HCF of two numbers

Explanation

  • Lines 5–10: We find all the divisors for the first input number.

  • Lines 13–16: We find all the divisors for the second ...