Problem 16:

*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}?

This was a problem I’d tried doing in Coldfusion a while ago, and gave up. The problem is that 2^{1000} 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])
print(x)

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.

### Like this:

Like Loading...

*Related*

[…] 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 |

[…] 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 |