Enumerable.Range.Aggregate方法处理长整数类型

时间:2014-02-09 16:22:11

标签: c# .net linq

我想解决Project Euler problem 20.

n! means n × (n − 1) × ... × 3 × 2 × 1

For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800,
and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.

Find the sum of the digits in the number 100!

我的代码返回错误的结果,因为它无法处理长整数类型。

        BigInteger x = Enumerable.Range(1, 100).Aggregate((total, next) => total * next);
        int[] y = Array.ConvertAll(x.ToString().ToArray(), a => (int)a);
        Console.WriteLine(y.Sum());

在某个步骤变量

  

变得非常大,然后它不是int类型。

我为Range编写了一个扩展,但是聚合方法很难。我的整个代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;

namespace p20
{
    class Program
    {
        // Find the sum of the digits in the number 100!
        static void Main(string[] args)
        {
            DigitsSum();
        }

        private static void DigitsSum()
        {
            BigInteger x = ExtentionLong.Range(1, 100).Aggregate((total, next) => total * next);
            int[] y = Array.ConvertAll(x.ToString().ToArray(), a => (int)a);
            Console.WriteLine(y.Sum());
            Console.Read();
        }
    }
    public static class ExtentionLong
    {
        public static IEnumerable<long> Range(this long source, long length)
        {
            for (long i = source; i < length; i++)
            {
                yield return i;
            }
        }
    }
}

1 个答案:

答案 0 :(得分:2)

需要进行两项更改

  • Select(i=>new BigInteger(i))
  • a => (int)(a-'0')

BigInteger x = Enumerable.Range(1, 10).Select(i=>new BigInteger(i)).Aggregate((total, next) => total * next);
int[] y = Array.ConvertAll(x.ToString().ToArray(), a => (int)(a-'0'));
Console.WriteLine(y.Sum());

BTW:你可以简单地这样做

var sum   = x.ToString().Sum(d => d - '0');