Python Program to Print the Fibonacci sequence
Last Updated :
28 Jul, 2023
The Fibonacci numbers are the numbers in the following integer sequence. 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, …….. In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation.
Fn = Fn-1 + Fn-2
with seed values : F0 = 0 and F1 = 1.
Fibonacci Numbers using Native Approach
Fibonacci series using a Python while loop is implemented.
Python3
n = 10
num1 = 0
num2 = 1
next_number = num2
count = 1
while count < = n:
print (next_number, end = " " )
count + = 1
num1, num2 = num2, next_number
next_number = num1 + num2
print ()
|
Output
1 2 3 5 8 13 21 34 55 89
Python Program for Fibonacci numbers using Recursion
Python Function to find the nth Fibonacci number using Python Recursion.
Python3
def Fibonacci(n):
if n < 0 :
print ( "Incorrect input" )
elif n = = 0 :
return 0
elif n = = 1 or n = = 2 :
return 1
else :
return Fibonacci(n - 1 ) + Fibonacci(n - 2 )
print (Fibonacci( 9 ))
|
Time complexity: O(2 ^ n) Exponential
Auxiliary Space: O(n)
Fibonacci Sequence using DP (Dynamic Programming)
Python Dynamic Programming takes 1st two Fibonacci numbers as 0 and 1.
Python3
FibArray = [ 0 , 1 ]
def fibonacci(n):
if n < 0 :
print ( "Incorrect input" )
elif n < len (FibArray):
return FibArray[n]
else :
FibArray.append(fibonacci(n - 1 ) + fibonacci(n - 2 ))
return FibArray[n]
print (fibonacci( 9 ))
|
Time complexity: O(n)
Auxiliary Space: O(n)
Optimization of Fibonacci sequence
Here, also Space Optimisation Taking 1st two Fibonacci numbers as 0 and 1.
Python3
def fibonacci(n):
a = 0
b = 1
if n < 0 :
print ( "Incorrect input" )
elif n = = 0 :
return 0
elif n = = 1 :
return b
else :
for i in range ( 1 , n):
c = a + b
a = b
b = c
return b
print (fibonacci( 9 ))
|
Time complexity: O(n)
Auxiliary Space: O(1)
Fibonacci Sequence using Cache
lru_cache will store the result so we don’t have to find Fibonacci for the same num again.
Python3
from functools import lru_cache
@lru_cache ( None )
def fibonacci(num: int ) - > int :
if num < 0 :
print ( "Incorrect input" )
return
elif num < 2 :
return num
return fibonacci(num - 1 ) + fibonacci(num - 2 )
print (fibonacci( 9 ))
|
Time complexity: O(n)
Auxiliary Space: O(n)
Fibonacci Sequence using Backtracking
Function for nth Fibonacci number using Backtracking.
Python3
def fibonacci(n, memo = {}):
if n < = 0 :
return 0
elif n = = 1 :
return 1
elif n in memo:
return memo[n]
else :
memo[n] = fibonacci(n - 1 ) + fibonacci(n - 2 )
return memo[n]
print (fibonacci( 9 ))
|
Time complexity: O(n)
Auxiliary Space: O(n)
Please refer complete article on the Program for Fibonacci numbers for more details!
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...