Efficient program for Fibonacci numbers
Question
Write a function that returns the th Fibonacci number, and comment on its efficiency.
Short answer
Iterate with two running values: time, space. The naive recursion recomputes subproblems and takes exponential time. Looping upward (or memoising) is linear, and matrix powering or fast-doubling gets arithmetic operations. Watch overflow: a signed 64-bit integer only holds values up to .
Adapted from Joshi, Denson & Downes, Quant Job Interview Questions and Answers, Q5.3, p.157; question and answer rewritten by SelfMadeQuant.com.
See the hint and the full worked solution in the question bank (free account).
Open the worked solution