This is a Python program to print nth Fibonacci number using dynamic programming with bottom-up approach.
Fibonacci numbers are defined by the sequence f(0) = 0, f(1) = 1 and f(n) = f(n – 1) + f(n – 2) for n >= 2. The program prompts the user to enter n and it prints the nth Fibonacci number.
1. The function fibonacci is defined.
2. fibonacci takes a number n and returns the nth Fibonacci number.
3. It creates a list r where r[n] will contain the nth Fibonacci number.
4. r[0] and r[1] are first initialized to 0 and 1 respectively.
5. The function then fills r by using the formula r[i] = r[i – 1] + r[i – 2].
6. The nth Fibonacci number is then returned.
Here is the source code of a Python program to print the nth Fibonacci number using dynamic programming with bottom-up approach. The program output is shown below.
def fibonacci(n): """Return the nth Fibonacci number.""" if n == 0: return 0 # r[i] will contain the ith Fibonacci number r = [-1]*(n + 1) r[0] = 0 r[1] = 1 for i in range(2, n + 1): r[i] = r[i - 1] + r[i - 2] return r[n] n = int(input('Enter n: ')) ans = fibonacci(n) print('The nth Fibonacci number:', ans)
1. The user is prompted to enter n.
2. fibonacci is called to compute the nth Fibonacci number.
3. The result is then displayed.
Case 1: Enter n: 7 The nth Fibonacci number: 13 Case 2: Enter n: 1 The nth Fibonacci number: 1 Case 3: Enter n: 3 The nth Fibonacci number: 2
Sanfoundry Global Education & Learning Series – Python Programs.
To practice all Python programs, here is complete set of 150+ Python Problems and Solutions.
- Practice Programming MCQs
- Apply for Python Internship
- Check Information Technology Books
- Apply for Programming Internship
- Check Python Books