There's no need for a loop to do this:
public static int SumOfEvenNumbersBetween(int start, int end)
{
if (end < start)
{
return SumOfEvenNumbersBetween(end, start);
}
if (start < 0)
{
if (end < 0) return -SumOfEvenNumbersBetween(-end, -start);
return SumOfEvenNumbersBetween(0, end) - SumOfEvenNumbersBetween(0, -start);
}
int m = (start - 1) / 2;
int n = end / 2;
return (n * (n + 1)) - (m * (m + 1));
}
Public Shared Function SumOfEvenNumbersBetween(ByVal startNumber As Integer, ByVal endNumber As Integer) As Integer
If endNumber < startNumber Then
Return SumOfEvenNumbersBetween(endNumber, startNumber)
End If
If startNumber < 0 Then
If endNumber < 0 Then
Return -SumOfEvenNumbersBetween(-endNumber, -startNumber)
End If
Return SumOfEvenNumbersBetween(0, endNumber) - SumOfEvenNumbersBetween(0, -startNumber)
End If
Dim m As Integer = (startNumber - 1) \ 2
Dim n As Integer = endNumber \ 2
Return (n * (n + 1)) - (m * (m + 1))
End Function
The sum of the first
n
positive even numbers is
n × (n + 1)
.
For positive ranges, you just need to calculate the sum of the first
n
even numbers, and then subtract the sum of the first
m
even numbers, where
m
is the number of even numbers before the start of your range.
For purely negative ranges, you just need to swap and negate the arguments, and then negate the answer. For example, the sum of the even numbers between
-9
and
-1
is the negative of the sum of the even numbers between
1
and
9
.
For ranges which straddle zero, break them into two parts, apply the previous rules, and then combine the results.
The code looks slightly more complicated than the loop / LINQ answers in
your reposted version of this question[
^], but for large ranges, it will be much faster.
EDIT: Added VB.NET version of the code to match the tags.