Project Euler #13

It's been a while since I did one of the Project Euler problems.  And since a lot of my work recently has been fixing bugs and working on some design documents, I was itching to do some "real" coding.  So it's on to problem #13.

Work out the first ten digits of the sum of the following one-hundred 50-digit numbers.

It would be nice if I could have stuck all of those numbers in an integer and simply added them up, but they were too big for that.  The solution I came up with kind of feels like I cheated a bit, but it gives me the correct answer!  What I did was take the list of 50-digit numbers and stick a decimal point in the middle (at the 25th character).  This gives me a number that .NET's double data type can handle.  I just had to make sure I removed the decimal point before grabbing my answer.

So my final solution was:

   1: string[] numbers = {
   2:     // giant list of numbers from website clipped
   3:                    };
   5: var list = from num in numbers
   6:            select double.Parse(num.Insert(25, "."));
   8: var sum = list.Sum();
   9: string answer = sum.ToString().Replace(".", "").Substring(0, 10);
Technorati Tags: ,,

1 Comment

  • Clever! I actually did the same problem a couple months ago, but I had created my own "large number" methods. I stored each number as an array of integers, hurting performance but giving me near limitless bounds. Very helpful for some of the other problems as well!

Comments have been disabled for this content.