Tuesday, October 03, 2006

Adding Up a Consecutive Range of Integers


 
Now, let's derive a formula for the more general case of summing the integers from M to N, where M <= N.
 
Well, we can write the Sum of M to N as: Sum(M,N) = Sum(1,N)  - Sum(1, M-1)
So, for example, the sum of 5-6 would be the sum from 1-6 minus the sum from 1-4.
 
We know that the Sum(1,N) would be N*(N+1)/2.  The Sum(1,M) would be M*(M+1)/2.
Then, the Sum(1,M-1) would be (M-1)*(M-1+1)/2, which simplifies to (M-1)*M/2, or
M*(M-1)/2.
 
Thus, the Sum(M,N) would be N*(N+1)/2 - M*(M-1)/2
 
So, the sum of 5-6 would be  6*7/2 - 5*4/2 = 21 - 10 = 11
 
Now, we can calculate the sum of any series of consecutive integers - even 5 to 10 million - in one step.
 
This is an example of simple elegance over brute force.

0 comments: