Fibonacci numbers
large n
algorithm efficiency
mathematical computation
recursive algorithms

Finding out nth fibonacci number for very large 'n'

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

Computing the nth Fibonacci number for very large n is mostly an algorithm-selection problem. The naive recursive formula is unusable at scale, and even linear iteration becomes too slow when n is enormous. For serious workloads, fast doubling or matrix exponentiation is the right tool because both reduce the time complexity to logarithmic in n.

Why Naive Recursion Fails

The textbook recurrence

F(n) = F(n - 1) + F(n - 2)

is mathematically correct, but a naive recursive implementation recomputes the same values repeatedly.

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

This grows exponentially and becomes useless very quickly.

Linear Iteration Is Better but Not Enough

An iterative version is already much better and uses O(n) time.

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
6
7
8print(fib_iter(10))

This works for moderately large n, but for extremely large values, linear time still becomes the bottleneck.

Use Fast Doubling

Fast doubling is the standard high-performance exact algorithm. It relies on these identities:

  • 'F(2k) = F(k) * (2 * F(k + 1) - F(k))'
  • 'F(2k + 1) = F(k + 1)^2 + F(k)^2'

That lets you compute the result in O(log n) recursive steps.

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

This is the best all-around answer for exact computation in languages with large integer support.

Matrix Exponentiation Is Another Logarithmic Option

Fibonacci numbers can also be generated using powers of the matrix:

[[1, 1], [1, 0]]

Exponentiating that matrix with repeated squaring also gives O(log n) time.

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
7
8def mat_pow(m, n):
9    result = [[1, 0], [0, 1]]
10    while n > 0:
11        if n & 1:
12            result = mat_mul(result, m)
13        m = mat_mul(m, m)
14        n >>= 1
15    return result
16
17
18def fib_matrix(n: int) -> int:
19    if n == 0:
20        return 0
21    return mat_pow([[1, 1], [1, 0]], n - 1)[0][0]

Matrix exponentiation is useful when you are already thinking in linear recurrences, but fast doubling is usually simpler to implement.

Very Large n Means Very Large Integers

Even with a logarithmic algorithm, the result itself becomes enormous. That means runtime is not only about the number of recursive steps, but also about large integer multiplication cost.

For exact F(n), the number of digits grows roughly linearly with n. So eventually the arithmetic on big integers becomes the dominant cost.

That is why a logarithmic algorithm is necessary but not magically free.

Modular Fibonacci for Competitive Programming

If the question only needs the result modulo some number, the problem becomes much easier to scale because integers stay bounded.

python
1def fib_mod(n: int, mod: 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) % mod)) % mod
7        d = (a * a + b * b) % mod
8        if k % 2 == 0:
9            return c, d
10        return d, (c + d) % mod
11
12    return helper(n)[0]

This version is common in algorithmic programming contests.

Common Pitfalls

  • Using naive recursion for anything beyond tiny input values.
  • Assuming linear iteration is sufficient for truly huge n.
  • Forgetting that the result size itself becomes enormous.
  • Choosing floating-point formulas when exact integer output is required.
  • Ignoring modular arithmetic when the task only asks for a remainder.

Summary

  • Naive recursion is mathematically simple but computationally impractical.
  • Linear iteration works only for moderate input sizes.
  • Fast doubling is usually the best exact algorithm for very large n.
  • Matrix exponentiation is another logarithmic-time solution.
  • For modulo problems, use the same ideas with bounded arithmetic.

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.