Interview Question

Senior Software Engineer Interview

how to add all the numbers from 1 to N

Answer

Interview Answer

3 Answers

0

the result is N*(N+1)/2
if you have to prove it, use induction

Kekeli on Mar 10, 2013
0

Kekell's solution is O(1) - if you get this question in an interview it's best to hem and haw while coding up the linear solution first, then dropping Gaussian summation.

function sum(n) {
   var sum = 0;
   for (var i=0; i <= n; i++) {
      sum += i;
   }
   return sum;
}
console.log(sum(100)); // 5050

Will run in O(n) time and O(1) space.

Dan on Jul 15, 2013
0

function sum(int n) {
    return (n==1) ? n : n + sum(n-1);
}

Matteo Gobbi on Apr 2, 2014

Add Answers or Comments

To comment on this, Sign In or Sign Up.