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:

          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?

Created: 8/26/2009 3:15:30 AM

Current Projects

I create content for .NET Core. My work appears in the .NET Core documentation site. I'm primarily responsible for the section that will help you learn C#.

All of these projects are Open Source (using the Creative Commons license for content, and the MIT license for code). If you would like to contribute, visit our GitHub Repository. Or, if you have questions, comments, or ideas for improvement, please create an issue for us.

I'm also the president of Humanitarian Toolbox. We build Open Source software that supports Humanitarian Disaster Relief efforts. We'd appreciate any help you can give to our projects. Look at our GitHub home page to see a list of our current projects. See what interests you, and dive in.

Or, if you have a group of volunteers, talk to us about hosting a codeathon event.