require 'prime' def d(n) divisors = [1] (2..Math.sqrt(n)).each do |possible_divisor| if n % possible_divisor == 0 divisors << possible_divisor divisors << (n / possible_divisor) end end divisors.inject(:+) end def amicable_numbers(n) d_values = {} (2..n).each do |num| d_values[num] = d(num) end possible_amicables = d_values.select{ |key, value| value <= n } amicables = [] possible_amicables.each do |key, value| if d_values[value] == key && key != value amicables << [key, value] end end amicables.flatten.uniq end puts amicable_numbers(100000).inject(:+)