Vasu Balakrishnan’s Blog

Project Euler #8

leave a comment »

 

Problem: Discover the largest product of five consecutive digits in the 1000-digit number.

Answer: 40824

Solution: First I created a helper routine GetNCharacters that would give me a list of N character length string. First I get a list of 5 consecutive characters, and for each item in that list I aggregate the individual character to get the product. See how I reuse the same helper routine inside.

private static IEnumerable<string> GetNCharacters(string pString, int pNumChars)
{
    for (int lStart = 0; lStart <= pString.Length - pNumChars; lStart++)
    {
        yield return pString.Substring(lStart, pNumChars);
    }
}

var lQuery = GetNCharacters(ReadFile("Problem8.txt"), 5)
                .Select(pArg => GetNCharacters(pArg, 1)
                                    .Aggregate(1, (pSeed, pId) => pSeed * pId[0].ToNumber()));
var lAnswer = lQuery.Max();

Time: 11 ms

Advertisements

Written by nbvasu

May 15, 2009 at 4:30 pm

Posted in C#, Euler

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: