Write a program to find the nth Fibonacci number using dynamic programming.
- User
Write a program to find the nth Fibonacci number using dynamic programming.
- Assistant
Here's a Python program that finds the nth Fibonacci number using dynamic programming:
def fibonacci(n): # Create an array to store the Fibonacci numbers fib = [0] * (n + 1) # Base cases fib[0] = 0 fib[1] = 1 # Compute Fibonacci numbers using dynamic programming for i in range(2, n + 1): fib[i] = fib[i - 1] + fib[i - 2] return fib[n] # Example usage n = 10 result = fibonacci(n) print(f"The {n}th Fibonacci number is: {result}")Explanation:
-
We define a function called
fibonaccithat takes an integernas input, representing the position of the Fibonacci number we want to find.
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.