Program to find the nth Fibonacci number using Python

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 to find the nth Fibonacci number using Python

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 to find the nth Fibonacci number using Python Output 1

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:

Program to find the nth Fibonacci number using Python Output 2

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).

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.