online advertising

Tuesday, August 27, 2013

Problem 8: Largest product in a series

Problem:

Please find the problem here.

Solution:

There are just 1000 - 5 + 1 = 996 cases to consider. The maximum possible value is $ 9 \times 9 \times 9 \times 9 \times 9 = 59049 $ so using a 32 bit integer is good enough.

Here is the code:


namespace Euler
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    internal static partial class Program
    {
        public static void Problem008()
        {
            string n = ReadResourceAsString("Euler.Problem008.txt");
            n = n.Replace("\n", string.Empty);
            n = n.Replace("\r", string.Empty);
            int[] d = n.ToCharArray().Select(c => c - '0').ToArray();
            int max = -1;
            for (int i = 0; i < 1000 - 5; i++)
            {
                int p = 1;
                for (int j = i; j < i + 5; j++)
                {
                    p *= d[j];
                }
                if (p > max)
                {
                    max = p;
                }
            }
            Console.WriteLine(max);
        }
    }
}

This problem is truly trivial, because it runs so quickly it doesn't worth to optimize it in any sense (one can imagine the next product can be obtained easily by division, or any product involve zero can quickly skip, ...)

Answer: 40824.

No comments :

Post a Comment