online advertising

Thursday, October 2, 2014

Problem 30 - Digit fifth powers

Problem:

Please find the problem here.

Solution:

The problem can be solved with brute force, just testing if the number matches the digit sum. The only problem is when do we stop the search.

Observe that the right hand side, despite raised to high power, are relatively small in magnitude since it got broken down into digits. For a six digit number, the maximum possible right hand side is
6x95 =354294, which is a 6 digit number, but 7x95 = 413343 is not a seven digit number. So all we need to do is to test the 6 digit numbers, in fact, only those less than 354294.

The rest is trivial. Caching the fifth powers of the digit can help quite a bit.

Code:

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

    internal static partial class Program
    {
        private class Solution030
        {
            public void Run()
            {
                Console.WriteLine(GetPowers().Aggregate((x, y) => x + y));
            }

            private IEnumerable<int> GetPowers()
            {
                int max = 9 * 9 * 9 * 9 * 9 * 6;
                int[] powers = Enumerable.Range(0, 10).Select(x => x * x * x * x * x).ToArray();
                for (int i = 1; i <= max; i++)
                {
                    IEnumerable<int> digits = i.ToString().Select(c => c - '0');
                    int digitPowerSum = digits.Select(d => powers[d]).Aggregate((x, y) => x + y);
                    if (digitPowerSum == i && i != 1)
                    {
                        yield return i;
                    }
                }
            }
        }

        public static void Problem030()
        {
            new Solution030().Run();
        }
    }
}

In fact, listing the found sums numbers is also fun:

4150 = 45 + 15 + 55 + 05
4151 = 45 + 15 + 55 + 15
54748 = 55 + 45 + 75 + 45 + 85
92727 = 95 + 25 + 75 + 25 + 75
93084 = 95 + 35 + 05 + 85 + 45
194979 = 15 + 95 + 45 + 95 + 75 + 95

Answer: 443839

No comments :

Post a Comment