Problem 48:

*The series, 1*^{1} + 2^{2} + 3^{3} + … + 10^{10} = 10405071317.

*Find the last ten digits of the series, 1*^{1} + 2^{2} + 3^{3} + … + 1000^{1000}.

Trying to do this one in CFML, on a Coldfusion 5 server, I get #INF, i.e. the CF server decides the number is too close to infinity and gives up! 1000^1000 is a number with 3000 zeroes in it, which is a pretty big number by all accounts. Python spits it out within a second without any problem. I’m really glad I decided to look at Python for these Project Euler problems; there are several where I could only go so far in CFML, knowing it wouldn’t work with the large numbers, but I think I’ll be able to complete in Python.

limit = 1000
sum = 0
for i in range(1, limit):
sum = sum + pow(i,i)
sumStr = str(sum)
length = len(sumStr)
lastTen = ''
for i in range(length-10, length):
lastTen += sumStr[i]
print(lastTen)

I don’t think this Python code is particularly good. I’m still struggling a bit to get my head around the range() function, and just how you do the basic things with strings. In CFML, I’d simply have said Right(sum, 10) to get the 10 right-most digits. I expect Python has similar, but I couldn’t find it after a quick look, so used the Range to loop 10 times towards the end of the *sum*, appending to a string.

### Like this:

Like Loading...

*Related*

you could have simply done sumStr[-10:] to print the last 10

Comment by Scala — March 2, 2009 @ 4:22 am |

Thanks for the tip. I’m still very new to Python syntax, so happy to get any advice on these things.

Comment by duncancumming — March 2, 2009 @ 7:58 am |

this is mine:

sum = 0

for i in range(1, 1000):

sum += i ** i

print str(sum)[-10:]

Comment by Connor — January 26, 2011 @ 4:11 am |

I don’t understand this.

the Python range function works like this:

range(start, n) -> it generates a range with (n-start) elements, from start to n-1!

example: range(1,5)= 1,2,3,4

Then the solution can not be correct, because 1000^1000 has not been calculated.

Am I wrong?

Comment by PJN — September 3, 2012 @ 6:31 pm |

Ugh, nevermind, I’m being slow today.

(for other slow people: the digits for 10^1 or 1000^1000 or 10000^1000000 are very much known)

Comment by PJN — September 3, 2012 @ 6:34 pm |

~~No, you must be correct. I’ve not got the code handy right now, so given that I did figure out the correct answer for this Project Euler question, can only assume the code was correct but the blog article is wrong for some reason!~~Comment by duncan — September 3, 2012 @ 10:55 pm |

[…] previously blogged about this Project Euler puzzle nearly 6 years ago, using Python. This is my approach using PHP as a simple practical exercise for myself, and I’d […]

Pingback by Project Euler: problem 48 (PHP) – Self powers | Duncan's blog — October 15, 2014 @ 8:02 am |