Skip to content

Efficient program for Fibonacci numbers

Question

Write a function that returns the nnth Fibonacci number, and comment on its efficiency.

Short answer

Iterate with two running values: O(n)O(n) time, O(1)O(1) space. The naive recursion F(n)=F(n−1)+F(n−2)F(n)=F(n-1)+F(n-2) recomputes subproblems and takes exponential time. Looping upward (or memoising) is linear, and 2×22\times2 matrix powering or fast-doubling gets O(log⁡n)O(\log n) arithmetic operations. Watch overflow: a signed 64-bit integer only holds values up to F92F_{92}.

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

Lessons behind this question