Permalink
Browse files

Problem 21

  • Loading branch information...
1 parent 0d3f300 commit a7b4984acf1be8cd8bfcfc79e82e3238f9a8dfa7 @mikelarkin committed Apr 12, 2012
Showing with 24 additions and 1 deletion.
  1. +24 −1 project_euler/problem_021.rb
@@ -6,4 +6,27 @@
#
# Evaluate the sum of all the amicable numbers under 10000.
#
-# Written by http://github.com/mikelarkin
+# Written by http://github.com/mikelarkin
+
+limit = (ARGV.empty? ? 10000 : ARGV[0].to_i)
+
+# Returns an array of proper divisors for a number
+def sum_of_proper_divisors(number)
+ divisors = []
+ 1.upto(number/2) do |n|
+ divisors << n if number % n == 0
+ end
+ return divisors.inject(0) {|sum, addend| sum + addend}
+end
+
+# Iterate up to the limit, finding amicable pairs
+pairs = []
+1.upto(limit) do |n|
+ sum = sum_of_proper_divisors(n)
+ pairs << [n, sum] if (sum != n) && (sum_of_proper_divisors(sum) == n)
+
+end
+
+pairs.flatten!
+pairs.uniq!
+puts "Sum of amicable pairs up to #{limit}: #{pairs.inject(0) {|sum, addend| sum + addend}}"

0 comments on commit a7b4984

Please sign in to comment.