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++)
{开发者_Python百科
n += i;
}
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;
}
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();
Yes
You can replace
int S = 0
for (int i = 0; i <= N; i++)
{
S += i;
}
with
int S = (N*(N+1))/2
As an added answer, there is also the Aggregate
function which is more general than Sum
:
var sum = Enumerable.Range(1, 10).Aggregate(0, (a, b) => a += b);
So you can also do stuff like
// multiply 1 * 2 * 3 * 4 ...
var product = Enumerable.Range(1, 10).Aggregate(1, (a, b) => a *= b);
What's the fascination with one liners? Here it is:
int n = 0; for (int i = 1; i <= 10; i++) {n += i;}
Is there a better way to calculate this? Sure. See the other answers that use a formula.
精彩评论