I really enjoy doing programming problems every now and then. Euler Problems range in difficulty and they are all math related. They are a great exercise for someone who knows math/logic and is trying to dabble with a new programming language. I’ve completed Euler problems 1-15 in C# and was working on tackling problem 16 today. For those too lazy to click the link, the problem is rather simple:

2

^{15}= 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 2^{1000}?

So the main problem with doing this in C# is that 2^{1000} is a pretty big number and there aren’t any simple data types in C# that can hold a number that large. So the next place I went was Python, where you don’t have to worry about overflow – it just takes care of things for you auto-magically.

The algorithm is pretty straightforward:

- Calculate/store 2
^{1000} - Convert it to a string
- Print it, just to see how big it is
- Instantiate a new variable for the sum of digits
- Loop over each character in the string
- Add the converted-to-int character to the rolling sum
- Print the sum for checking

1 2 3 4 5 6 7 |
bigNumber = 2 ** 1000 str_bigNumber = str(bigNumber) print bigNumber digitSum = 0 for dig in str_bigNumber: digitSum += int(dig) print digitSum |

Dang, Python is fast! You can even use an online interpreter (I didn’t feel like downloading it).

Here is how I solved it in Python back when I was working through these problems:

def solve(n):

return sum([int(s) for s in str(2**n)])

assert(solve(15) == 26)

print solve(1000)

A bit more elegant than my solution … I love one-liners!

Yeah, Python lends itself well to some really nice one-liners, with things like: lambda functions, list-comprehensions, and the trusty ol’ map() function. When I was doing the Euler problems, I made it a point to solve each one in a Pythonic way whenever possible. I also put together a little framework with an ‘EulerProblem’ class and a test harness, using Python’s ‘unittest’ library, that goes through each EulerProblem and tests it’s solve() method using the examples from each problem.

One of my favorites was probably problem #13 (http://goo.gl/ZbdOk):

def solve(fileName):

return int(str(sum([int(line) for line in open(fileName).readlines()]))[:10])

where filename is just a txt file containing the one hundred 50-digit numbers.