Jump Trading Interview Question

Write codes for the Nth Fibonacci number.

Interview Answers

Anonymous

Mar 14, 2012

You were actually asked to write two versions, one is the recursive one, and the other non-recursive. Then explain why the recursive one is very bad.

1

Anonymous

Sep 13, 2014

The recursive solution is terrible, because it takes exponential time. The iterative solution isn't bad - this takes O(n) time. It's possible to do O(log n) time using Binet's formula.

1

Anonymous

Sep 19, 2012

int fib_rec(int n) { switch(n) { case 0: return 0; case 1: return 1; } return fib_rec(n-2) + fib_rec(n-1); } int fib_iter(int n) { switch(n) { case 0: return 0; case 1: return 1; } int f0=0; int f1=1; for(int i=2;i<=n;++i) { int f2=f0+f1; f0=f1; f1=f2; } return f1; }

1