Python Program to Implement the Fibonacci Sequence Using Dynamic Programming

 

 

Problem Statement

The Fibonacci sequence is a series of numbers in which each number (after the first two) is the sum of the two preceding ones. The sequence commonly starts with 0 and 1. The problem is to calculate the nth Fibonacci number efficiently using dynamic programming techniques.

Approach Explanation

This problem can be solved efficiently using dynamic programming by storing the results of previously calculated Fibonacci numbers to avoid redundant calculations. This method ensures that we calculate each Fibonacci number only once.

Dynamic Programming Structure:

  1. Define a list fib where fib[i] represents the ith Fibonacci number.
  2. Initialize the first two Fibonacci numbers: fib[0] = 0 and fib[1] = 1.
  3. Iterate from 2 to n, computing each Fibonacci number as the sum of the two preceding numbers.
  4. The final answer will be in fib[n].

Time Complexity:

O(n), where n is the position in the Fibonacci sequence.

Space Complexity:

O(n) for storing the Fibonacci numbers in the list.

Python Code


def fibonacci(n):
    """
    Function to compute the nth Fibonacci number using dynamic programming.

    Args:
    n (int): The position in the Fibonacci sequence.

    Returns:
    int: The nth Fibonacci number.
    """
    if n < 0:
        raise ValueError("Input should be a non-negative integer.")
    
    if n == 0:
        return 0
    elif n == 1:
        return 1

    # Create a list to store Fibonacci numbers up to n
    fib = [0] * (n + 1)
    fib[0] = 0
    fib[1] = 1

    # Compute Fibonacci numbers from 2 to n
    for i in range(2, n + 1):
        fib[i] = fib[i - 1] + fib[i - 2]

    return fib[n]


# Example usage
position = 10
fib_number = fibonacci(position)

print("The {}th Fibonacci number is: {}".format(position, fib_number))
    

Explanation of the Program

Let’s break down the structure of the program:

1. Input:

The input consists of an integer representing the position in the Fibonacci sequence:

    position = 10

2. Error Handling:

The program checks if the input is a non-negative integer and raises an error if the input is invalid.

3. List Initialization:

A list fib is created with length n + 1, initialized to 0. The first two Fibonacci numbers are set: fib[0] is 0 and fib[1] is 1.

4. Computing Fibonacci Numbers:

The program iterates from 2 to n, calculating each Fibonacci number as the sum of the two preceding numbers, storing the result in the fib list.

5. Final Result:

The nth Fibonacci number can be found in fib[n].

Example Execution:

For the provided input, the output will display the nth Fibonacci number:

The 10th Fibonacci number is: 55

This indicates that the 10th Fibonacci number is 55.

 

Leave a Reply

Your email address will not be published. Required fields are marked *