Skip to content

Instantly share code, notes, and snippets.

@jakedobkin
Created December 31, 2011 23:38
Show Gist options
  • Save jakedobkin/1545655 to your computer and use it in GitHub Desktop.
Save jakedobkin/1545655 to your computer and use it in GitHub Desktop.
Euler 92
# http://projecteuler.net/problem=92
# this version takes advantage of the fact that all numbers up to 10MM have roundfadds < 600
# so first compute those, then check them for each number from 1 to 10MM
# that shaves it from 6 minutes to 120s
def fadd(n):
sum = 0
for i in range (0,len(str(n))):
sum += int(str(n)[i:i+1])**2
return sum
def roundfadd(n):
if array[n] != 0:
return array[n]
if fadd(n) == 1:
return 1
elif fadd(n) == 89:
return 89
else:
return roundfadd(fadd(n))
array = [0]*600
for x in range (1,600):
array[x]=roundfadd(x)
top = 10000000
count = 0
for r in range (1,top):
if array[fadd(r)] == 89:
count += 1
print count
@djacobs
Copy link

djacobs commented Jan 2, 2012

def fadd(n):
    sum = 0
    while n > 0:
        sum += (n%10)**2
        n = ((n-(n%10))/10)
    return sum

@djacobs
Copy link

djacobs commented Jan 2, 2012

changing fadd to the above cut about processing time from ~160s to 40s on my macbook air. There's also a similar solution here:
http://rosettacode.org/wiki/Happy_Number#Python

@jakedobkin
Copy link
Author

jakedobkin commented Jan 2, 2012 via email

@djacobs
Copy link

djacobs commented Jan 2, 2012 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment