Project Euler Problem #16:

Problem #16 is another example of how some problems are much simpler in certain languages than other languages, and like Problem #13, it is a possible contender for the simplest Project Euler question. The question reads:

Project Euler Problem 16: Power digit sum
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?

Because 2^1000 is an integer, it makes sense to store its value in the “int” data type. Unfortunately, most programming languages only give “int” variables 32 bits, meaning that values greater than 2^31 will not be stored accurately. Luckily, this isn’t an issue in Python 2.7. Here is my solution to this problem:

Solution #1: Brute Force Approach

We simply store the value of 2^1000, convert it to a string, and then add up each digit in the string. Here is an implementation of this method in Python 2.7:

 '''
 Author: Walker Kroubalkian
 Brute Force Approach to Project Euler Problem #16
 '''
 import time
 def projectEulerProblemSixteen(m,n):
     a = str(m**n)
     total = 0
     for c in a:
         total+=int(c)
     return total
 start = time.time()
 print projectEulerProblemSixteen(2, 1000)
 print ("--- %s seconds ---" % (time.time()-start))
 '''
 Prints
 1366
 --- 0.000135898590088 seconds ---
 for input of m=2, n=1000
 '''

Of course, if we were working in a different programming language, this would take a bit more work, such as casting 2^1000 as a long or something of that sort. Otherwise, this problem is quite simple.

That’s all for today. Thanks for reading!

Published by Walker Kroubalkian

My name is Walker Kroubalkian. I really enjoy math, computer science, and hiking.

Leave a comment

Design a site like this with WordPress.com
Get started