Finding the factorial for a number using Aggregate in LINQ C#

The Aggregate LINQ operator allows you to define your own aggregation function to be performed on a sequence. The function is performed on each element and the result of the function is passed into the next iteration. The final result of the operation is returned at the end.

To calculate the factorial of 5, i.e. 5!, we’d calculate 5x4x3x2x1 or 1x2x3x4x5, doesn’t matter. The first overload of the operator accepts a Function of int, int, int, i.e. it takes two integers and returns an integer.

Here’s how we can calculate 5!:

IEnumerable<int> ints = Enumerable.Range(1, 5);
int factorial = ints.Aggregate((f, s) => f * s);

…which correctly gives 120. ‘f’ is the aggregate value and ‘s’ is the current element in the lambda expression.

The following is performed step by step:

  1. The first iteration passes in f = 1 and s = 2, which yields 1×2 = 2
  2. In the second iteration f is the result of the first iteration, i.e. 2 and s will be the second element, i.e. 3, yielding 2×3 = 6
  3. Then it continues with f = 6 from the second operation and taking 4 from the integer sequence, giving 6×4 = 24
  4. Finally we get 24×5 = 120

View the list of posts on LINQ here.

Advertisements

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

5 Responses to Finding the factorial for a number using Aggregate in LINQ C#

  1. I think, in the first iteration, it is f = 1, s = 2;

    Consider the following program:

    IEnumerable ints = Enumerable.Range(1, 5);
    int factorial = ints.Aggregate((f, s) => { Console.WriteLine(“{0}, {1}”, f, s); return f * s; } );

    Output:
    1, 2
    2, 3
    6, 4
    24, 5

    • Andras Nemes says:

      You’re correct, I’ll update the post.
      Thanks for your input.
      //Andras

    • Umer says:

      It is giving the following error:
      ‘System.Collections.IEnumerable’ does not contain a definition for ‘Aggregate’ and no extension method ‘Aggregate’ accepting a first argument of type ‘System.Collections.IEnumerable’ could be found (are you missing a using directive or an assembly reference?)

    • Noor says:

      It is giving the following Error:

      ‘System.Collections.IEnumerable’ does not contain a definition for ‘Aggregate’ and no extension method ‘Aggregate’ accepting a first argument of type ‘System.Collections.IEnumerable’ could be found (are you missing a using directive or an assembly reference?)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

ultimatemindsettoday

A great WordPress.com site

Elliot Balynn's Blog

A directory of wonderful thoughts

Robin Sedlaczek's Blog

Developer on Microsoft Technologies

HarsH ReaLiTy

A Good Blog is Hard to Find

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

the software architecture

thoughts, ideas, diagrams,enterprise code, design pattern , solution designs

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

Anything around ASP.NET MVC,WEB API, WCF, Entity Framework & AngularJS

Cyber Matters

Bite-size insight on Cyber Security for the not too technical.

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: