Yahoo Interview Question: Write a function given x, the... | Glassdoor

## Interview Question

Intern Interview(Student Candidate) Sunnyvale, CA

# Write a function given x, the function returns the xth

number in the Fibonacci sequence.

2

int getNthFib(int n) {
// assume n is positive
if (n &lt;= 2) return n;
int i = 1;
int j = 2;
int k;
count = 2;
while (count &lt; n) {
k = i + j:
count ++;
i = j;
j = k;
}
return k;

HappyCoder on Nov 2, 2009
1

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 &lt;= 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
2

Prior to your next interview, I would also google &quot;tail recursion&quot; and demonstrate how more efficient a tail recursive fibonacci sequence would be.

Anonymous on Dec 14, 2009
0

#include
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&lt;

HarishIITR on Jan 11, 2012