views:

204

answers:

3

I'm looking for a method to do calculations like:

function 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.

+6  A: 
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).

squelart
This misses the line that attributes this formula to Carl Friedrich Gauss.
Tomalak
+8  A: 

Of course it is!

1+2+3+...+n = n * (n+1) / 2
nico
nico is right! You better use a mathematical function wherever possible because they represent a shorter way to some complex calculation which otherwise will require loops and/or recursion.If you need high performance in a calculation, try to find it in a mathematical function as the above!
Leni Kirilov
+2  A: 

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!

filip-fku
Pass 100000 to that and enjoy :)
nico
I think the enjoyment is more in writing it and thinking about the magic rather than watching it do its thing! :)
filip-fku
this is awful... such an easy mathematical function should not be calculated with recursion. huge performance hit with large number parameter!
Leni Kirilov
@ilip-fku: I was being ironic... I'm not gonna test it, but having 100000 levels of recursions will just freeze your browser and make your users angry :)
nico
Oh I agree with that completely! I mentioned it more for the educational value than anything else
filip-fku
Your function fails for zero.
starblue
+1 for thinking outside the box... As others complain, this solution certainly wouldn't make sense in real life, but this type of reasoning could lead to good solutions to other problems.
squelart