Oxaric’s Blog

A compendium of amazing things…

Euler Project Problem #21 Solution

Posted by oxaric on November 24, 2008

It uses Ruby.


Click to directly download euler-solution-21.rb

# filename 'euler-solution-21.rb'
# By: Louis Casillas, oxaric@gmail.com

# Euler Problem #21
# Evaluate the sum of amicable numbers under 10000
# d(n) = sum of the divisors of n
# Numbers are amicable if d(a) = b and d(b) = a, where a is not b

def d( num )
   
   sum = 0
   i = 1   
   half_num = ( num / 2 )
   
   if (num % 2) == 0
      adder = 1
   else
      adder = 2
   end
   

   while i <= half_num
      if (num % i) == 0
         sum += i
      end      
   
      i += adder
   end

   sum
end

UPTO = 10000
array_of_used_numbers = Array.new()
sum = 0

for i in (2...UPTO)
   a = d(i)
   b = d(a)

   if (!= b) && (== b)
      is_new_one = true

      for j in (0...array_of_used_numbers.size)
         if (== array_of_used_numbers[j]) || (== array_of_used_numbers[j])
            is_new_one = false
         end
      end
      
      if is_new_one
         array_of_used_numbers.insert( 0, i )         
         array_of_used_numbers.insert( 0, a )
         array_of_used_numbers.insert( 0, b )
         sum += ( i + a )         
      end
   end
end

puts "The sum is: " + sum.to_s

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>