Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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
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.
