Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accumulating sum in one line in C#

Tags:

c#

algorithm

Is it possible to do this in one line with the goal of getting the accumulated sum equal to n?

int n = 0;
for (int i = 1; i <= 10; i++)
{
    n += i;
}
like image 818
Morgan Herlocker Avatar asked Apr 13 '11 17:04

Morgan Herlocker


2 Answers

There's a LINQ extension method for that:

static int SlowSum1ToN(int N)
{
    return Enumerable.Range(1, N).Sum();
}

However, you can also calculate this particular value (the sum of an arithmetic sequence) without iterating at all:

static int FastSum1ToN(int N)
{
    return (N * (1 + N)) / 2;
}
like image 81
Dan Tao Avatar answered Oct 19 '22 22:10

Dan Tao


Yes it's possible, you can do that using Enumerable.Range to generate a sequence of integer numbers and then call the LINQ extension method Sum as the following:

int result = Enumerable.Range(1, 10).Sum();
like image 28
Homam Avatar answered Oct 19 '22 23:10

Homam