[Project Euler] Problem 49

Problem Description

The arithmetic sequence, 1487, 4817, 8147, in which each of the terms increases by 3330, is unusual in two ways: (i) each of the three terms are prime, and, (ii) each of the 4-digit numbers are permutations of one another.

There are no arithmetic sequences made up of three 1-, 2-, or 3-digit primes, exhibiting this property, but there is one other 4-digit increasing sequence.

What 12-digit number do you form by concatenating the three terms in this sequence?

C#

使用C#处理这类问题,是相当爽的。Because CSharp has LINQ!

解决这道题的思路是这样:

  1. 找出1001到9999中所有的素数;
  2. 基于第一步找出的素数数组,进行分组,分组的依据是,如果两个数所用的字符集相同,不如1013和1031属于一组,因为它们的字符集都是{0, 1, 1, 3};
  3. 筛选出每一组里面长度大于等于3的组;
  4. 针对步骤3的结果的每一组,看是否满足题目要求,这一步就比较简单了;

代码如下:

        public static void Run()
        {
            // generate primes from 1001 to 9999
            var primeList = GeneratePrimeList();

            // use linq to get the valid list in which each element has 3 or more numbers which are permutations of each other
            var groupedList = from item in primeList
                         group item by Convert.ToInt32(string.Concat(item.ToString().ToCharArray().OrderBy<char, char>(c => c))) into itemGroup
                         where itemGroup.Count() >= 3
                         select itemGroup;

            // check each group and output the result
            groupedList.ToList().ForEach((ig) => CheckAndOutputIsValid(ig));
        }

It looks so simple and so fantastic, isn’t it? LINQ is amazing!

CheckAndOutputIsValid

        private static void CheckAndOutputIsValid(IGrouping<int, int> ig)
        {
            List<int> offsetList = new List<int>();

            int count = ig.Count();
            for (int i = 1; i < count - 1; i++)
            {
                offsetList.Clear();

                for (int j = 0; j <count; j++)
                {
                    if (j == i) continue;
                    int offset = j > i ? ig.ElementAt(j) - ig.ElementAt(i) : ig.ElementAt(i) - ig.ElementAt(j);

                    offsetList.Add(offset);
                }

                // check if there have equal offsets
                var result = from item in offsetList
                             group item by item into itemGroup
                             where itemGroup.Count() >= 2
                             select itemGroup;

                // output the valid result
                if (result.Count() > 0)
                {
                    int middle = ig.ElementAt(i);
                    int offset = result.First().Key;
                    Console.WriteLine("{0}, {1}, {2}, offset={3}", middle - offset, middle, middle + offset, offset);
                }
            }
        }
原文地址:https://www.cnblogs.com/quark/p/2555032.html