Yahoo
3.4 of 5 1,598 reviews
www.yahoo.com Sunnyvale, CA 5000+ Employees

Yahoo Senior Software Engineer Interview Question

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

Part of a Senior Software Engineer Interview Review - one of 488 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 Flag Response
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 Flag Response
0
of 0
votes
function sum(int n) {
    return (n==1) ? n : n + sum(n-1);
}
- Matteo Gobbi on Apr 2, 2014 Flag Response

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.

Glassdoor is your free inside look at Yahoo interview questions and advice. All interview reviews posted anonymously by Yahoo employees and interview candidates.