Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the sum of consecutive whole numbers w/o using loop in JavaScript

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.

like image 225
Z. Zlatev Avatar asked May 16 '10 08:05

Z. Zlatev


2 Answers

Of course it is!

1+2+3+...+n = n * (n+1) / 2
like image 147
nico Avatar answered Sep 30 '22 17:09

nico


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

like image 33
squelart Avatar answered Sep 30 '22 19:09

squelart