Duncan's blog

January 25, 2009

Project Euler: problem 16

Filed under: Project Euler,Python — duncan @ 8:10 pm
Tags: , ,

Problem 16:

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?

This was a problem I’d tried doing in Coldfusion a while ago, and gave up. The problem is that 21000 is a 302-digit number. Coldfusion supports 32-bit integers, between -2,147,483,648 and 2,147,483,647. Even a 64-bit integer wouldn’t be long enough.

I briefly tried something in Javascript, then turned to Python, which I’ve never used before. So the following is my first ever Python program! Probably a few lines longer than it needs to be; I later saw solutions expressed in one line.

x = 0
y = repr(pow(2,1000))
length = len(y)

for i in range(length)
	x = x + int(y[i])


This was exactly what I’d tried and failed to do with CFML. After installing Python 3.0, skimming through the tutorial and reading a few other bits in the documentation, I was able to put the above together and get the solution pretty quickly.

Although Python is dynamically-typed, you still have to cast a numeric value to a string and a string to an int, using repr() and int() respectively. In Coldfusion there’s no need to do that; I can create a string, then perform arithmetic directly on it (if it’s a numeric value in the string), then check the length of the string, append another string, find the square root, etc. all without having had to cast or convert it at any stage.

Apart from that, I like what I see of Python so far. I’m a stickler for good indentation normally, so I don’t see the requirement to indent as being a problem. I’ll maybe see if I can use Python to solve some of the other Project Euler problems that I’ve not been able to finish due to Coldfusion’s limitations with long integers.



  1. […] code to problem 16. I work out 100!, then I turn the number into a string, work out the length of the string, loop […]

    Pingback by Project Euler: problem 20 « Duncan’s blog — January 26, 2009 @ 12:33 am | Reply

  2. […] previously blogged about this Project Euler puzzle nearly 6 years ago. Initially I tried solving it using ColdFusion, but its native functions couldn’t handle the […]

    Pingback by Project Euler: problem 16 (PHP) | Duncan's blog — October 1, 2014 @ 8:03 am | Reply

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: