Select Page

Program to find the nth Fibonacci number using Python

by | Jan 31, 2021 | Python Programs

Home » Python » Python Programs » 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

```Program 1: Recursion
def fibo(m):
if m < 0:
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:
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).

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

Author

• A Full Stack Developer with 10+ years of experience in technical content creation.