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

Yahoo Intern Interview Question (student candidate)

I interviewed in Sunnyvale, CA and was asked:
"Write a function given x, the function returns the xth number in the Fibonacci sequence."
Add Tags [?]
Answer Flag Question

Part of a Intern Interview Review - one of 488 Yahoo Interview Reviews

Answers & Comments

1
of 1
vote
int getNthFib(int n) {
// assume n is positive
if (n <= 2) return n;
int i = 1;
int j = 2;
int k;
count = 2;
while (count < n) {
  k = i + j:
  count ++;
  i = j;
  j = k;
}
return k;
- HappyCoder on Nov 2, 2009 Flag Response
1
of 2
votes
I've been asked this question several times at interviews, and it's usually associated with recursion, so the answer most would like to see is like:

int getFib(int n) {
    return n <= 1 ? n : getFib(n - 1) + getFib(n - 2);
}

The interviewer will also want to know you understand that recursion would be slow for high values of n.
- Anonymous on Dec 13, 2009 Flag Response
2
of 2
votes
Prior to your next interview, I would also google "tail recursion" and demonstrate how more efficient a tail recursive fibonacci sequence would be.
- Anonymous on Dec 14, 2009 Flag Response
0
of 0
votes
#include<iostream>
using namespace std;

int getFib(int n) {
    if(n==1||n==2) return n;
    return getFib(n-1)+getFib(n-2);
}

int main(){
    int n=6;
    cout<<getFib(5)<<endl;
    system("pause");
    return 0;
    }
- HarishIITR on Jan 11, 2012 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.