4 * Calculate the sum of a given range of integer numbers.
6 * Somewhat of a more subtle way of calculation - and it even has a story
9 * Supposedly during math classes in elementary school, the teacher of
10 * young mathematician Gauss gave the class an assignment to calculate the
11 * sum of all natural numbers between 1 and 100, hoping that this task would
12 * keep the kids occupied for some time. The story goes that Gauss had the
13 * result ready after only a few minutes. What he had written on his black
14 * board was something like this:
23 * s = (1/2) * 100 * 101 = 5050
25 * A more general form of this formula would be
27 * s = (1/2) * (max + min) * (max - min + 1)
29 * which is used in the piece of code below to implement the requested
30 * function in constant time, i.e. without dependencies on the size of the
38 int gauss_get_sum (int min
, int max
)
40 /* This algorithm doesn't work well with invalid range specifications
41 so we're intercepting them here. */
47 return (int) ((max
+ min
) * (double) (max
- min
+ 1) / 2);