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;
}
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With