The Gaussian formula can be generalized to find the sum of any set of consecutive integers from a to b, i.e., a, a+1, a+2, ... b-1, b, where a < b.

For our first generalization let us assume the set consists of positive integers only (a > 0). To calculate the result, we subtract the sum of numbers from 1 to b from the sum of the numbers going from 1 to a - 1:

    sum = (b(b + 1) - (a - 1)(a - 1 + 1)) / 2

This can be simplified to:

    sum = (b + a)(b - a + 1) / 2

Secondly, we need to find the generalization for the case where a and b are negative integers. All we have to do is count the sum of all integers between -b and -a, then reverse the sign. That gives us:

    sum = -(-a + (-b))((-a) - (-b) + 1) / 2

That simplifies to:

    sum = (b + a)(b - a + 1) / 2
Finally, if a is negative and b is positive, we simply need to count the sum of all integers between 1 and -a and subtract it from the sum of integers between 1 and b. That looks like this:
    sum = (b(b + 1) - (-a)(-a + 1)) / 2

This can be simplified to:

    sum = (b + a)(b - a + 1) / 2

Obviously, if a equals -b, the sum is zero, and need not be calculated (though the formula will still work, of course).

As you can see, in all three cases we have obtained the same formula:


        sum = (b + a)(b - a + 1) / 2