How to Calculate the nth Fibonacci Number in Python
How to Calculate the nth Fibonacci Number in Python
How to Calculate the nth Fibonacci Number in Python
I need to calculate the nth Fibonacci number. How can I implement this efficiently in Python?
solveurit24@gmail.com Changed status to publish February 16, 2025
The Fibonacci sequence is a series where each number is the sum of the two preceding ones.
- Using Iterative Approach:
- Efficient and avoids the exponential time complexity of the recursive approach.
- Code Example:
- Explanation:
def fibonacci(n): if n <= 0: return "Invalid input" elif n == 1: return 0 elif n == 2: return 1 a, b = 0, 1 for _ in range(2, n): a, b = b, a + b return b print(fibonacci(10)) # Output: 34- The iterative approach calculates the Fibonacci number in O(n) time.
- Handles edge cases for invalid input and small values of n.
solveurit24@gmail.com Changed status to publish February 16, 2025