Tuesday, September 16, 2008

Problem 21 Project Euler Amicable Numbers

[root@www ~]# python twentyone.py
started at: Tue Sep 16 11:32:37 2008
31626
Ended at: Tue Sep 16 11:33:15 2008
[root@www ~]# cat twentyone.py
# -*- coding: utf-8 -*-
"""
<+ MODULE_NAME +>
Project Euler Problem Set
<+ DESCRIPTION +>
Solutions in Python to the problems at http://projecteuler.net

Licensed under the Creative Commons license; see http://creativecommons.org for more details. In short, this means you can freely reuse, modify and distribute this program, also commercially, for as long you provide a proper attribution.

Copyright by Jonathan Mark, jonathanmark.com/aristede.com, jmark@aristede.com

>>> print 881 + 1
882

"""
import time
starttime = time.asctime()
print "started at: ",starttime
class Numbers:
"""Class for solving Problem 21 in Project Euler"""
def sumFactors(self,n):
"""Function to determine common factors

>>> t = Numbers()
>>> t.sumFactors(28)
28
"""
return sum(filter(lambda i: n%i == 0,range(1,n/2 + 1)))

def amicable(self,n,m):
""" Function to test for amicable pairs

>>> t = Numbers()
>>> t.amicable(220,284)
True

>>> t = Numbers()
>>> t.amicable(284,220)
True

>>> t = Numbers()
>>> t.amicable(6,6)
False

>>> t = Numbers()
>>> t.amicable(8,7)
False

"""
return (self.sumFactors(n) == m) and (self.sumFactors(m) == n) and (n != m)

def filterNonAmicable(self,seq):
""" Function to remove non-members of amicable pairs

>>> t = Numbers()
>>> t.filterNonAmicable(range(219,222))
[220]

>>> t = Numbers()
>>> t.filterNonAmicable(range(4))
[]
"""

return filter(lambda i: self.amicable(i,self.sumFactors(i)),seq)

t = Numbers()
print sum(t.filterNonAmicable(range(10000)))


print "Ended at: ",time.asctime()

if __name__ == "__main__":
import doctest
doctest.testmod()

No comments: