Parallel Computing
Fibonacci Sequence
Algorithm Optimization
Multithreading
High-Performance Computing

Parallelize Fibonacci sequence generator

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 is a classic example in concurrency discussions because the recursive definition looks like a tree of independent work. That appearance is misleading. If your goal is to generate the sequence in order, the fastest solution is usually a simple iterative loop. Parallelism only becomes reasonable in narrower cases, such as evaluating many independent Fibonacci requests or demonstrating task scheduling.

Distinguish Sequence Generation from Single-Value Computation

When people say "parallelize Fibonacci", they often mean one of two different problems:

  1. generate the ordered sequence 0, 1, 1, 2, 3, 5, ...
  2. compute one large fib(n)

The sequence generator is naturally incremental because each term depends on the previous two. An iterative implementation is already optimal enough for most applications:

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

Trying to parallelize this exact loop usually adds overhead without removing meaningful work.

Parallelize Independent Tasks Instead

If you need several unrelated Fibonacci values, those requests can be distributed across processes. That is a much better workload shape than parallelizing a single naive recursive tree.

python
1from concurrent.futures import ProcessPoolExecutor
2
3def fib_iterative(n: int) -> int:
4    a, b = 0, 1
5    for _ in range(n):
6        a, b = b, a + b
7    return a
8
9
10def compute_many(values: list[int]) -> list[int]:
11    with ProcessPoolExecutor() as executor:
12        return list(executor.map(fib_iterative, values))
13
14
15print(compute_many([100000, 100001, 100002]))

Each process handles one independent request, so the coordination cost is easier to justify.

Why Naive Recursive Parallelism Is Usually a Trap

The textbook recursive definition repeats the same work many times:

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

You can split the two recursive branches into parallel tasks, but that only parallelizes an already wasteful algorithm. The runtime still explodes because the same subproblems are recomputed over and over.

Before reaching for threads or processes, fix the algorithm first. Memoization or dynamic programming almost always buys more than parallelism here.

Use Memoization for Single Values

If your actual goal is one large fib(n), caching is a better first step.

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

This still uses the recursive definition, but it removes repeated work. In practice that turns a toy example into something usable much faster than naive parallel recursion.

If You Still Need Parallelism, Bound It

There are valid cases where you want a parallel recursive demonstration. In those cases, use a cutoff so that only large branches become tasks while small branches fall back to sequential computation.

python
1from concurrent.futures import ProcessPoolExecutor
2
3def fib_seq(n: int) -> int:
4    a, b = 0, 1
5    for _ in range(n):
6        a, b = b, a + b
7    return a
8
9
10def fib_parallel_top(n: int, cutoff: int = 30) -> int:
11    if n < cutoff:
12        return fib_seq(n)
13
14    with ProcessPoolExecutor(max_workers=2) as executor:
15        left = executor.submit(fib_seq, n - 1)
16        right = executor.submit(fib_seq, n - 2)
17        return left.result() + right.result()
18
19
20print(fib_parallel_top(35))

This example is intentionally limited. It parallelizes only the top split and uses a sequential routine below the cutoff. That makes the overhead predictable, even if it is still not the best way to compute Fibonacci in production.

Common Pitfalls

The most common mistake is parallelizing the naive recursive algorithm before removing duplicate subproblems. More workers do not fix exponential waste.

Another issue is using Python threads for CPU-bound Fibonacci code. Because of the GIL, threads are not the right tool for this workload. Use processes for CPU-bound work or switch to a runtime with a different threading model.

People also often benchmark on inputs that are too small. At that scale, process startup and scheduling costs dominate, which makes parallel code look worse than it would on larger independent tasks.

Finally, sequence generation and independent request handling are not the same problem. Generating one ordered sequence is inherently simple and sequential, while evaluating many unrelated fib(n) requests can be a reasonable parallel workload.

Summary

  • Generating the Fibonacci sequence in order is usually best done iteratively.
  • Parallelism is more useful for many independent Fibonacci requests than for one sequence loop.
  • Fix the algorithm with memoization or dynamic programming before adding concurrency.
  • Use processes, not threads, for CPU-bound Fibonacci work in Python.
  • If you parallelize a recursive version, use a cutoff so task overhead does not dominate.

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.