My solutions to the problems found at Project Euler.

Jump to: | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 16 | 17 | 20 | 21 | 22 | 25 | 3-2 |

Problem 21


#! /usr/bin/python
# Problem: 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.
#
# Plan: Re-use old divsiors code from other problem, eliminate the number being divided from the list,
#       and the rest is just taking their definition of d, implementing it, and then counting. 
#       Easy-peasy, nothing clever here.

import math

def divisors(n):
  """ Return a list of divisors for n. """
  sqrtn = int(math.sqrt(n))
  divisors = []
  
  if sqrtn ** 2 == n:
    divisors.append(sqrtn)
    
  for number in xrange(1,sqrtn):
    if n % number == 0:
      divisors.append(number)
      divisors.append(n/number)
  
  if n in divisors:
    divisors.remove(n)
    
  return divisors
  
def d(n):
    return sum(divisors(n))
    
def amicable(a):
    b = d(a)
    if d(b) == a and not a == b:
        return (a,b)
    
    return False


if __name__ == "__main__":
    numbers = []
    for n in xrange(10000):
        a = amicable(n)
        if a:
            if not a[0] in numbers:
                numbers.append(a[0])
            if not a[1] in numbers:
                numbers.append(a[1])
    
    print sum(numbers)
     

jb