Search code examples
c#castingrangeaggregateenumerable

C# can cast LINQ Aggregate to double to output factorial, this works for integer up to 12


I want to fill the list with factorials using linq. I got this, this works up to 12. I assume it's because of the integer range. But I couldn't retype it to double. Can this be easily modified (retyped)?

var listOfFactorials = from fact in Enumerable.Range(0, 171).Reverse().ToList() select new { Number = fact, Factorial = (fact == 0) ? 1d : Enumerable.Range(1, fact).Aggregate((i, j) => (i * j))};

I want to have the list filled with factorials up to the number 170. I don't need it for anything, just playing for fun :)


Solution

  • You have to use BigInteger:

    var listOfFactorials = from fact in Enumerable.Range(0, 200).Reverse().ToList()
                            select new 
                            { 
                                Number = fact, 
                                Factorial = (fact == 0) ? BigInteger.One : Enumerable.Range(1, fact)
                                                                                     .Select( i => new BigInteger(i))
                                                                                     .Aggregate((i, j) => (i * j))
                            };