Python Program for Fibonacci numbers

The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones. In this article, we will learn different approaches to compute the nth Fibonacci number in Python.

Problem statement − Our task is to compute the nth Fibonacci number.

The sequence Fn of Fibonacci numbers is given by the recurrence relation:

Fn = Fn-1 + Fn-2

with seed values:

F0 = 0 and F1 = 1

We have two main approaches to solve this problem:

  • Recursive approach
  • Dynamic programming approach

Using Recursive Approach

The recursive approach directly implements the mathematical definition of Fibonacci numbers ?

# Recursive approach
def fibonacci_recursive(n):
    if n 

Fibonacci(10) = 55

Note: This approach has exponential time complexity O(2^n) as it recalculates the same values multiple times.

Using Dynamic Programming Approach

The dynamic programming approach stores previously calculated values to avoid redundant calculations ?

# Dynamic programming approach with memoization
def fibonacci_dp(n, memo={}):
    if n 

Fibonacci(10) = 55

Iterative Approach (Most Efficient)

An iterative solution that builds up from the base cases ?

# Iterative approach
def fibonacci_iterative(n):
    if n 

Fibonacci(10) = 55

Comparison of Approaches

Approach Time Complexity Space Complexity Best For
Recursive O(2^n) O(n) Learning concept
Dynamic Programming O(n) O(n) Multiple queries
Iterative O(n) O(1) Single computation

Fibonacci Sequence Visualization

Fibonacci Sequence: F(n) = F(n-1) + F(n-2) F(0) 0 F(1) 1 F(2) 1 F(3) 2 F(4) 3 F(5) 5 F(6) 8 ... 1+0=1 1+1=2 ? Base cases ? Calculated values ? Addition operation

Conclusion

The iterative approach is the most efficient for single Fibonacci calculations with O(n) time and O(1) space complexity. Use dynamic programming with memoization when you need to compute multiple Fibonacci numbers. The recursive approach, while intuitive, should be avoided for large numbers due to its exponential time complexity.

Updated on: 2026-03-25T06:28:38+05:30

765 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements