Yahoo

  www.yahoo.com
Work in HR? Unlock Free Profile

Yahoo Senior Software Engineer Interview Question

"how to add all the numbers from 1 to N"
Add Tags [?]
Answer

Part of a Senior Software Engineer Interview Review - one of 536 Yahoo Interview Reviews

Answers & Comments

0
of 0
votes

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

- Kekeli on Mar 10, 2013
0
of 0
votes

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
of 0
votes

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

- Matteo Gobbi on Apr 2, 2014

To comment on this question, Sign In with Facebook or Sign Up

Tags are like keywords that help categorize interview questions that have something in common.