How to Calculate the nth Fibonacci Number in Python

76 views

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
0

The Fibonacci sequence is a series where each number is the sum of the two preceding ones.

  1. Using Iterative Approach:
    • Efficient and avoids the exponential time complexity of the recursive approach.
  2. Code Example:
  3. 
    
    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
    

    Explanation:

    • 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
0
You are viewing 1 out of 1 answers, click here to view all answers.