Table of Contents
Introduction
In this section, we will understand the python code to print nth Fibonacci number of the given number. The expression for Fibonacci number is:
F(n) = F(n-1) + F(n-2)
Given, F(0) = 0 and F(1) = 1
Program
Program 1: Recursion def fibo(m): if m < 0: print("Please enter the valid input!") elif m == 1: # F(0) is 0 return 0 elif m == 2: # F(1) is 1 return 1 else: # Recurrence relation return fibo(m-1)+fibo(m-2) n = int(input("Please enter the integer value to find nth Fibonacci number: ")) print("The Fibonacci number corresponding to", n, "is", fibo(n))
Output
Program 2: Dynamic programming
def fibo(m): f_array = [0, 1] if m < 0: print("Please enter the valid input!") elif m <= len(f_array): return f_array[m-1] else: temp = fibo(m-1) + fibo(m-2) f_array.append(temp) return temp n = int(input("Please enter the integer value to find nth Fibonacci number: ")) print("The Fibonacci number corresponding to", n, "is", fibo(n))
Output:
Explanation
In the above program, we have created a variable n to take the positive integer input from the user. The fibo() function calculates the nth Fibonacci number by relation F(n-1) + F(n-2).
0 Comments