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.
Python Program for n-th Fibonacci number Using recursion
Here we will use recursion function. The code defines a function Fibonacci(n) that calculates the nth Fibonacci number recursively. It checks for invalid input and returns the Fibonacci number based on the base cases (0 and 1) or by recursively calling itself with reduced values of n. The driver program prints the 10th Fibonacci number.
Python3
def Fibonacci(n):
if n< = 0 :
print ( "Incorrect input" )
elif n = = 1 :
return 0
elif n = = 2 :
return 1
else :
return Fibonacci(n - 1 ) + Fibonacci(n - 2 )
print (Fibonacci( 10 ))
|
Time Complexity: O(2N)
Auxiliary Space: O(N)
Python Program for n-th Fibonacci number Using Dynamic Programming
The code defines a function fibonacci(n) that calculates the nth Fibonacci number using dynamic programming. It initializes a list FibArray with the first two Fibonacci numbers (0 and 1). The function checks if the Fibonacci number for n is already present in FibArray and returns it. Otherwise, it calculates the Fibonacci number recursively, stores it in FibArray for future use, and returns the calculated value. The driver program prints the 9th Fibonacci number using this approach.
Python3
FibArray = [ 0 , 1 ]
def fibonacci(n):
if n< 0 :
print ( "Incorrect input" )
elif n< = len (FibArray):
return FibArray[n - 1 ]
else :
temp_fib = fibonacci(n - 1 ) + fibonacci(n - 2 )
FibArray.append(temp_fib)
return temp_fib
print (fibonacci( 9 ))
|
Time Complexity: O(N)
Auxiliary Space: O(N)
n-th Fibonacci number Using Dynamic Programming with Space Optimization
Python3
def fibonacci(n):
a = 0
b = 1
if n < 0 :
print ( "Incorrect input" )
elif n = = 0 :
return a
elif n = = 1 :
return b
else :
for i in range ( 2 , n):
c = a + b
a = b
b = c
return b
print (fibonacci( 9 ))
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Python Program for n-th Fibonacci number Using Using Arrays
The code defines a function fibonacci(n) that calculates the nth Fibonacci number by creating an array data containing the Fibonacci sequence up to the nth number. It initializes data with the first two Fibonacci numbers (0 and 1) and then iteratively calculates the subsequent numbers. The function returns the nth number from data. The driver program prints the 9th Fibonacci number using this approach.
Python3
def fibonacci(n):
if n < = 0 :
return "Incorrect Output"
data = [ 0 , 1 ]
if n > 2 :
for i in range ( 2 , n):
data.append(data[i - 1 ] + data[i - 2 ])
return data[n - 1 ]
print (fibonacci( 9 ))
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Explanation:
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144]
As we know that the Fibonacci series is the sum of the previous two terms, so if we enter 12 as the input in the program, so we should get 144 as the output. And that is what is the result.
Python Program for n-th Fibonacci number Using Direct Formula
The formula for finding the n-th Fibonacci number is as follows:

Python3
from math import sqrt
def nthFib(n):
res = ((( 1 + sqrt( 5 )) * * n) - (( 1 - sqrt( 5 ))) * * n) / ( 2 * * n * sqrt( 5 ))
print ( int (res), 'is' , str (n) + 'th fibonacci number' )
nthFib( 12 )
|
Output
144 is 12th fibonacci number
Time Complexity: O(1)
Auxiliary Space: O(1)
Python Program for n-th Fibonacci number Using power of the matrix {{1, 1}, {1, 0}}
This is another O(n) that relies on the fact that if we n times multiply the matrix M = {{1,1},{1,0}} to itself (in other words calculate power(M, n)), then we get the (n+1)th Fibonacci number as the element at row and column (0, 0) in the resultant matrix.
The matrix representation gives the following closed expression for the Fibonacci numbers:
Python
def fib(n):
F = [[ 1 , 1 ],
[ 1 , 0 ]]
if (n = = 0 ):
return 0
power(F, n - 1 )
return F[ 0 ][ 0 ]
def multiply(F, M):
x = (F[ 0 ][ 0 ] * M[ 0 ][ 0 ] + F[ 0 ][ 1 ] * M[ 1 ][ 0 ])
y = (F[ 0 ][ 0 ] * M[ 0 ][ 1 ] + F[ 0 ][ 1 ] * M[ 1 ][ 1 ])
z = (F[ 1 ][ 0 ] * M[ 0 ][ 0 ] + F[ 1 ][ 1 ] * M[ 1 ][ 0 ])
w = (F[ 1 ][ 0 ] * M[ 0 ][ 1 ] + F[ 1 ][ 1 ] * M[ 1 ][ 1 ])
F[ 0 ][ 0 ] = x
F[ 0 ][ 1 ] = y
F[ 1 ][ 0 ] = z
F[ 1 ][ 1 ] = w
def power(F, n):
M = [[ 1 , 1 ], [ 1 , 0 ]]
for i in range ( 2 , n + 1 ):
multiply(F, M)
if __name__ = = "__main__" :
n = 9
print (fib(n))
|
Time Complexity: O(n)
Auxiliary Space: O(1)
Optimization of above methods
W can optimized to work in O(Logn) time complexity. We can do recursive multiplication to get power(M, n) in the previous method.
Steps:
- To optimize method 6, we need to just change the power function of the method 6.
- In method 6, the power function takes O(n) time for which the time complexity of the whole program becomes O(n).
- In this method, we modify the power function using recursion, calling (F and n//2) which makes n half at each calling and achieve time complexity of O(log N).
Python3
def fib(n):
F = [[ 1 , 1 ],
[ 1 , 0 ]]
if (n = = 0 ):
return 0
power(F, n - 1 )
return F[ 0 ][ 0 ]
def multiply(F, M):
x = (F[ 0 ][ 0 ] * M[ 0 ][ 0 ] +
F[ 0 ][ 1 ] * M[ 1 ][ 0 ])
y = (F[ 0 ][ 0 ] * M[ 0 ][ 1 ] +
F[ 0 ][ 1 ] * M[ 1 ][ 1 ])
z = (F[ 1 ][ 0 ] * M[ 0 ][ 0 ] +
F[ 1 ][ 1 ] * M[ 1 ][ 0 ])
w = (F[ 1 ][ 0 ] * M[ 0 ][ 1 ] +
F[ 1 ][ 1 ] * M[ 1 ][ 1 ])
F[ 0 ][ 0 ] = x
F[ 0 ][ 1 ] = y
F[ 1 ][ 0 ] = z
F[ 1 ][ 1 ] = w
def power(F, n):
if (n = = 0 or n = = 1 ):
return
M = [[ 1 , 1 ],
[ 1 , 0 ]]
power(F, n / / 2 )
multiply(F, F)
if (n % 2 ! = 0 ):
multiply(F, M)
if __name__ = = "__main__" :
n = 5
print (fib(n))
|
Time Complexity: O(log N)
Auxiliary Space: O(log N), if we consider the function call stack size, otherwise O(1).
Please refer complete article on Program for Fibonacci numbers for more details!
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
26 Jun, 2023
Like Article
Save Article