Skip to content

Instantly share code, notes, and snippets.

@rjmunro
Forked from anonymous/friendly.py
Last active December 10, 2015 09:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rjmunro/4416265 to your computer and use it in GitHub Desktop.
Save rjmunro/4416265 to your computer and use it in GitHub Desktop.
def memoize(f):
cache= {}
def memf(*x):
if x not in cache:
cache[x] = f(*x)
return cache[x]
return memf
@memoize
def sum_factors(x):
# Factors are either less than the square root and paired with a number
# greater than the square root, or the square root itself
sum = 1
j = 2
square = 4
# Find factors less than the square root
while square < x:
if x%j==0:
sum += j
sum += x/j
# Find next square using: (x + 1)**2 = (x**2 + 2*x + 1)
square += j + j + 1
j += 1
# Add the square root itself
if square == x:
sum += j
return sum
def friendly_numbers(limit):
for n in range(1,limit):
friend=sum_factors(n)
friendliest=sum_factors(friend)
if n==friendliest and n!=friend:
print n, "and", friend, "are besties!"
friendly_numbers(5000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment