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 to Display Fibonacci Sequence Using Recursion
The Fibonacci sequence is a series where each number is the sum of the two preceding numbers, starting from 0 and 1. We can generate this sequence using recursion, where a function calls itself until it reaches a base case.
Fibonacci Recursion Logic
The recursive approach works by breaking down the problem:
- Base case: If n ? 1, return n
- Recursive case: Return fibonacci(n-1) + fibonacci(n-2)
Example
def fibonacci_recursion(n):
if n <= 1:
return n
else:
return fibonacci_recursion(n-1) + fibonacci_recursion(n-2)
num_terms = 12
if num_terms <= 0:
print("Enter a positive integer")
else:
print("The fibonacci sequence is:")
for i in range(num_terms):
print(fibonacci_recursion(i))
Output
The fibonacci sequence is: 0 1 1 2 3 5 8 13 21 34 55 89
How It Works
Let's trace how fibonacci_recursion(4) works:
Performance Consideration
While elegant, recursive Fibonacci has exponential time complexity O(2^n) due to repeated calculations. For large values, consider using memoization or iteration for better performance.
Conclusion
Recursive Fibonacci demonstrates the power of recursion by breaking complex problems into simpler subproblems. However, for practical applications, consider optimized approaches like memoization to avoid redundant calculations.
