I'm looking for a method to do calculations like:
f开发者_JS百科unction sumIntegerUpTo(number) {
return 1+2+3+...+number;
}
If you pass number
as 5
function should return the sum of 1+2+3+4+5
. I'm wondering if it's possible to do without loops.
Of course it is!
1+2+3+...+n = n * (n+1) / 2
function sumIntegerUpTo(number) {
return (1 + number) * number / 2;
}
I can think of two easy ways for me to remember this formula:
Think about adding numbers from both ends of the sequence: 1 and n, 2 and n-1, 3 and n-2, etc. Each of these little sums ends up being equal to n+1. Both ends will end at the middle (average) of the sequence, so there should be n/2 of them in total. So sum = (n+1) * (n/2).
There are as many number before the average (which is (1+n)/2) as there are after, and adding a pair of numbers that are equidistant to this average always results in twice the average, and there are n/2 pairs, so sum = (n+1)/2 * 2 * n/2 = (n+1)/2*n.
You can fairly easily extend the above reasoning to a different starting number, giving you: sum(numbers from a to b, inclusive) = (a+b)/2*(b-a+1).
Or you can use a recursive approach - which here is redundant given there is a simple formula! But there is always something cool and magical about recursion!
function addToN(n)
{
if(n==0) return 0;
else return n + addToN(n-1);
}
Edited to deal with 0!
精彩评论