Saturday, October 11, 2008

Project Euler Sum Of Powers Problem 30

[root@www ~]# python thirty.py
4150
4151
54748
92727
93084
194979
The total is 443839
Started at: Sat Oct 11 10:53:50 2008 Ended at: Sat Oct 11 10:54:01 2008
[root@www ~]# cat thirty.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()

# A 7 digit number must equal at least 1,000,000.
# The sum of the fifth powers of a 7-digit number cannot be
# greater than 7*9**5 equals about 420,000.
# Using similar reasoning n > 7, no number which equals the sum
# of the fifth powers of its digits can have more than six digits.

def sumOfPowers(p,n):
"""takes each digit of a number, raises it to the pth power,
and sums it.

>>> sumOfPowers(5,123)
276

"""

s = str(n)
tot = 0
for i in range(len(s)):
tot += int(s[i])**p
return tot

sum = 0
for n in range(2, 1000000):
if n == sumOfPowers(5,n):
print n
sum += n

print "The total is", sum






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

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

No comments: