euler/euler021.rb

32 lines
627 B
Ruby
Raw Normal View History

2014-04-25 23:59:14 +00:00
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(:+)