Done puzzle 45
[project-euler.git] / euler21.rb
1 load 'primes.rb'
2 load 'divisors.rb'
3
4 require 'logger'
5 $log = Logger.new(STDERR)
6 $log.level = Logger::WARN
7
8 def amicable_pairs(limit)
9 cache = [0,0]
10 2.upto(limit) do |n|
11 cache << n.sum_of_proper_divisors
12 $log.debug { "Sum of proper divisors of #{n} is #{n.sum_of_proper_divisors}" }
13 end
14 amicable_pairs = []
15 2.upto(limit) do |n|
16 if cache[cache[n]] == n and cache[n] > n
17 amicable_pairs << [n, cache[n]]
18 $log.info { "Found amicable pairs #{n} and #{cache[n]}" }
19 end
20 end
21 amicable_pairs
22 end
23
24 def sum_of_amicable_pairs(limit)
25 amicable_pairs(limit).reduce(0) {|a, p| a += p.reduce(:+)}
26 end
27
28 if __FILE__==$0
29 puts sum_of_amicable_pairs 10000
30 end
31
32 $log.close