We don't need no steenkin' loops; the old Greeks even knew that; here's how: suppose you want to add the numbers 1 ... 6; you can visualize it like this:
|
Code:
|
*
**
***
****
*****
****** |
... now add that same tirangle to the original one but upside down:
|
Code:
|
*######
**#####
***####
****###
*****##
******# |
So twice the number we want to know (let the number be 'n') equals n*(n+1),
so the sum of the numbers 1 ... n equals n*(n+1)/2
That is easy enough to turn into a little method:
|
Code:
|
int sum(int n) {
return n*(n+1)/2; |
If we want to know the sum of the numbers m ... n we actually want to know the sum of the numbers 1 ... n minus the sum of the numbers 1 ... m-1. In Java that makes:
|
Code:
|
int sum(int m, int n) {
return sum(n)-sum(m-1);
} |
Now that wasn't too difficult was it?
kind regards,
Jos