Fibonacci
Algorithm
Mathematics
Sequence
Computation

Efficient calculation of Fibonacci series

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

Fibonacci numbers are a classic example for comparing algorithmic efficiency. A naive recursive implementation is simple but grows exponentially and becomes unusable for larger indices. Efficient methods range from linear iterative loops to logarithmic fast doubling techniques.

Baseline Recursive Approach

The direct recursive definition is readable but slow.

python
1def fib_recursive(n: int) -> int:
2    if n < 2:
3        return n
4    return fib_recursive(n - 1) + fib_recursive(n - 2)

Time complexity is exponential due to repeated subproblems.

Dynamic Programming with Memoization

Memoization avoids recomputation.

python
1from functools import lru_cache
2
3@lru_cache(maxsize=None)
4def fib_memo(n: int) -> int:
5    if n < 2:
6        return n
7    return fib_memo(n - 1) + fib_memo(n - 2)

This reduces complexity to linear time with linear memory.

Iterative Linear-Time Method

For most practical uses, iterative approach is simple and fast.

python
1def fib_iter(n: int) -> int:
2    a, b = 0, 1
3    for _ in range(n):
4        a, b = b, a + b
5    return a

Complexity:

  • time O(n)
  • space O(1)

This is usually the best default implementation.

Fast Doubling in Logarithmic Time

Fast doubling computes pair values recursively with divide-and-conquer.

python
1def fib_fast_doubling(n: int) -> int:
2    def helper(k: int):
3        if k == 0:
4            return (0, 1)
5        a, b = helper(k // 2)
6        c = a * (2 * b - a)
7        d = a * a + b * b
8        if k % 2 == 0:
9            return (c, d)
10        return (d, c + d)
11
12    return helper(n)[0]

Complexity:

  • time O(log n)
  • space O(log n) from recursion stack

This is excellent for very large n.

Batch Generation of Sequence Values

If you need first k Fibonacci numbers, generate once iteratively.

python
1def fib_sequence(k: int):
2    seq = []
3    a, b = 0, 1
4    for _ in range(k):
5        seq.append(a)
6        a, b = b, a + b
7    return seq
8
9print(fib_sequence(10))

Avoid recomputing each value independently.

Big Integer and Performance Considerations

Python supports arbitrary-precision integers, so very large Fibonacci numbers are possible, but arithmetic cost grows with digit count. For huge indices, algorithm choice and memory behavior matter more than micro-optimizing loops.

Benchmark with realistic n values before choosing advanced implementation.

Matrix Exponentiation Approach

Another logarithmic strategy uses matrix powers. It is mathematically elegant and useful in algorithm education.

python
1def mat_mul(a, b):
2    return [
3        [a[0][0]*b[0][0] + a[0][1]*b[1][0], a[0][0]*b[0][1] + a[0][1]*b[1][1]],
4        [a[1][0]*b[0][0] + a[1][1]*b[1][0], a[1][0]*b[0][1] + a[1][1]*b[1][1]],
5    ]
6
7def mat_pow(m, n):
8    res = [[1, 0], [0, 1]]
9    while n:
10        if n & 1:
11            res = mat_mul(res, m)
12        m = mat_mul(m, m)
13        n >>= 1
14    return res
15
16def fib_matrix(n):
17    if n == 0:
18        return 0
19    m = [[1, 1], [1, 0]]
20    return mat_pow(m, n - 1)[0][0]

Modular Fibonacci for Competitive Programming

When only remainder is needed, apply modulo during each arithmetic operation to keep numbers bounded and fast. This is critical in programming contests and cryptographic toy examples.

Benchmark with Multiple Sizes

Evaluate methods on small, medium, and large indices to understand crossover points. Fast doubling usually wins for large n, while iterative code may be simpler and sufficient for moderate values.

Common Pitfalls

  • Using naive recursion for large n and hitting extreme runtimes.
  • Comparing algorithms without controlling for interpreter overhead.
  • Recomputing sequence prefixes repeatedly in loops.
  • Ignoring integer growth cost for very large indices.
  • Overcomplicating implementation when linear iterative method is sufficient.

Summary

  • Naive recursion is educational but inefficient.
  • Memoization and iterative methods provide practical linear-time solutions.
  • Fast doubling gives logarithmic-time performance for large indices.
  • Generate sequences iteratively when multiple values are needed.
  • Choose algorithm based on input size and operational constraints.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.