Sunday, November 4, 2012

Project Euler Problem 16

This time, it is kinda easy. Without any optimization effort in my part, I thought about it without reference from books or website. In the question, we can see the problem was about getting 2^n, and then the result's digits been added up / summed up. So, this is what I do in turns.

1. First try to get the 2^15 part right. Display result to check. I used BigInteger instantly because it already have pow() method.
2. We need to divide the digits. One of the way would be using result%10, result%100, etc... But that seems harsh. So I thought that maybe we can divide them using the available substring method. Convert the current BigInteger to String using toString(), then substring() them in a for loop. ParseInt() to change into integer (because it is single digit, it is save to use int for this part of operation), then sum it into sum.

Test sample:


Looking pretty good to me.

3. Finally, change n to 1000. At first, I put 100, so I got wrong answer. I was a bit confused, until I check it again. Human error, tsk tsk tsk. Put a time test. Wow 2 secs. I guess there are faster algorithm, but I don't feel like looking for it right now.

This is the final program:

No comments:

Post a Comment