Cover Image for Python program to find the nth Fibonacci Number
235 views

Python program to find the nth Fibonacci Number

You can find the nth Fibonacci number in Python using various methods, including recursion, iterative loops, and dynamic programming. Here are a few examples:

  1. Using Recursion: The Fibonacci sequence can be defined recursively as follows:
   def fibonacci_recursive(n):
       if n <= 0:
           return 0
       elif n == 1:
           return 1
       else:
           return fibonacci_recursive(n - 1) + fibonacci_recursive(n - 2)

   # Find the nth Fibonacci number
   n = 10  # Change this to the desired value of n
   nth_fibonacci = fibonacci_recursive(n)
   print(f"The {n}th Fibonacci number is {nth_fibonacci}")

Be cautious when using recursion for large values of n as it can lead to a significant performance hit due to repeated calculations.

  1. Using Iteration: You can calculate the nth Fibonacci number iteratively using a loop:
   def fibonacci_iterative(n):
       if n <= 0:
           return 0
       elif n == 1:
           return 1
       else:
           a, b = 0, 1
           for _ in range(2, n + 1):
               a, b = b, a + b
           return b

   # Find the nth Fibonacci number
   n = 10  # Change this to the desired value of n
   nth_fibonacci = fibonacci_iterative(n)
   print(f"The {n}th Fibonacci number is {nth_fibonacci}")

This iterative approach is more efficient than the recursive one for large n values.

  1. Using Memoization (Dynamic Programming): You can optimize the recursive approach using memoization to store and reuse previously calculated Fibonacci numbers:
   def fibonacci_memoization(n, memo={}):
       if n <= 0:
           return 0
       elif n == 1:
           return 1
       elif n in memo:
           return memo[n]
       else:
           memo[n] = fibonacci_memoization(n - 1, memo) + fibonacci_memoization(n - 2, memo)
           return memo[n]

   # Find the nth Fibonacci number
   n = 10  # Change this to the desired value of n
   nth_fibonacci = fibonacci_memoization(n)
   print(f"The {n}th Fibonacci number is {nth_fibonacci}")

Memoization improves the performance of the recursive solution by avoiding redundant calculations.

Choose the method that best suits your needs, depending on the desired value of n and the efficiency requirements of your application.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS