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?

Published 25 August 2009 11:15 PM by wwagner
Ads by Lake Quincy Media

Comments

# John Donnelly said on 26 August, 2009 11:47 AM

Sweet! Can you explain the "little math".. I'm not sure I get the (long)Math.Pow(10, 11- Index)

# wwagner said on 26 August, 2009 02:13 PM

The 'little math' shifts each digit left by the correct number of decimal places.  The first character of each string is multiplied by 10^11, the second by 10^10, etc.  Until the last character I add (the 11th) is not shifted at all.

# Chris Lomont said on 04 September, 2009 08:33 AM

Your reasoning is incorrect. Here is a counterexample to your method. Suppose the first number is 1 followed by 49 nines, the next 48 numbers are 1 followed by 49 zeros, and the last number is 1 followed by 48 zeros and a 1. Adding the prefixes only gives answer 5099999999 while adding the entire numbers gives 5100000000. You cannot add prefixes of numbers and guarantee a carry from arbitrarily far back does not affect the outcome.

It works on this set of numbers because you got lucky. The method is wrong.

It's simple and fast enough to just implement arbitrary length addition in a few lines of code, which is the correct way to solve this problem.

Search

Go

Blog Group Links

Nascar style badges