Long time, no Euler (or YAEPS # 13)
Well, it’s been a long time since I’ve taken the time to solve and blog about one of the Euler problems. It was time to pick this up again.
Problem 13 says:
Work out the first 10 digits of the sum of the following one-hundred 50-digit numbers. <long list of numbers elided>
The key here is that you only need the first 10 digits of the answer. Therefore, you only need to add the first 11 digits for each of the 100 numbers. Here’s why: These numbers do not contain any 0’s in the first position. Therefore, the sum of all the first digits is at least 100. The first digit contributes at least 3 digits in the final answer. Once you get to the 11th digit, that number can’t be great than 900. (100 9’s). It won’t affect anything in the first 10 digits. That’s the end of the work.
That makes the final answer one LINQ query:
1: static void Main(string[] args)
2: {
3: var finalAnswer = (from index in Enumerable.Range(0, 11)
4: from s in listOfDigits
5: select int.Parse(s[index].ToString()) *
6: (long)Math.Pow(10, 11 - index)).
7: Sum();
8: Console.WriteLine(finalAnswer);
9: }
listOfDigits (elided) is a list of strings where each string contains the digits for one number.
The first line of the query creates an enumeration for the first 11 digits.
The next two lines select a single character from each string, parsing that character to create an integer.
Next, do a little math to move that single digit into the correct column for the sum.
Finally, sum all the integers.
Sweet, huh?