If you intend to solve the problem on your own, I wouldn’t recommend reading any further.
Let
be defined as the sum of proper divisors of
(numbers less than
which divide evenly into
).
Ifand
, where
, 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
. The proper divisors of 284 are 1, 2, 4, 71 and 142; so
.
Evaluate the sum of all the amicable numbers under 10000.
def d(n) total = 0 1.upto n/2 do |i| if (n % i) == 0 total += i end end total end amicable_sum = 0 10000.times do |a| b = d(a) if d(b) == a && b > a amicable_sum += a + b end end puts amicable_sum
My version of isn’t as efficient as the one in the PDF you get after solving the problem, but it gets the job done.
Running it takes around 8.5 seconds on my machine. That’s not too bad for ~20 lines of code.
Tags: project euler, ruby, snippet