code a function that returns the nth fibnocci number... coded it the most efficient way by using 3 variable... Then the interviewer wrote the recursive form and asked me what are the pros and cons of your(iterative) approach and recursive approach.
Hint:
Definition:
F(n) = 0 (n=0); 1 (n=1); F(n-1)+F(n-2) (n>1)
Cons of recursive approach
1. The OS stack which keep track of function calls may overflow if n is very large
2. In recursive approach if we want to solve F(N) then we need to solve F(N-1) and F(N-2)and in order to solve F(N-1) we have to solve F(N-2) AND F(N-3). So we are solving F(N-2) two times once while solving F(N) and second while solving F(N-1). This is highly inefficient.
Saturday, October 18, 2008
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment