gpt-4-0314· OpenAI
Arena Human Preference 55K
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 (bottom-up approach):
def fibonacci(n): fib = [0, 1] # Generate Fibonacci numbers from 2 to n for i in range(2, n+1): fib.append(fib[i-1] + fib[i-2]) return fib[n] # Test the function n = int(input("Enter the value of n: ")) result = fibonacci(n) print(f"The {n}th Fibonacci number is: {result}")This program uses a loop to calculate Fibonacci numbers from 2 to n and stores them in a list called
fib. The nth Fibonacci number is then returned from the list. Unlike the recursive approach, this method does not require redundant calculations and has a time complexity of O(n).
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.