Overview

 

Question

Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n). If d(a) = b and d(b) = a, where a b, then a and b are an amicable pair and each of a and b are called amicable numbers. For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220. Evaluate the sum of all the amicable numbers under 10000.

click for answer

31626

Solutions

 

Ruby

 amicableSums.rb https://raw.github.com/addamh/euler/master/021/amicableSums.rb download
#!/usr/bin/env ruby

final_sum=0
    
2.upto(9999) do |a|
  sum1=0
  1.upto(a/2) do |b|
    if a%b == 0
      sum1+=b
    end
  end
  sum2=0
  if sum1<a 
    1.upto(sum1/2) do |c|
      if sum1%c == 0
        sum2+=c
      end
    end
    if sum2==a
      final_sum+=a
      final_sum+=sum1
    end
  end
end

puts final_sum
$ time ruby amicableSums.rb
real	0m6.545s
user	0m6.520s
sys	0m0.022s