How to solve Euler Problem 16: Python

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:

215 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 21000?

So the main problem with doing this in C# is that 21000 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:

  1. Calculate/store 21000
  2. Convert it to a string
  3. Print it, just to see how big it is
  4. Instantiate a new variable for the sum of digits
  5. Loop over each character in the string
  6. Add the converted-to-int character to the rolling sum
  7. Print the sum for checking

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

Posted in Professional Tagged with: , ,
3 comments on “How to solve Euler Problem 16: Python
  1. puremcc says:

    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)

    • brhlavinka says:

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

      • Mike Duffy says:

        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.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

Subscribe to my Insights via Email

Join 61 other subscribers

%d bloggers like this: