Python Program for n-th Fibonacci number
Last Updated :
16 Sep, 2024
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.
The formula for finding the n-th Fibonacci number is as follows:
[Tex]\normalsize Fibonacci\ number\ F_n\\ (1)\ F_n=F_{n-1}+F_{n-2},\hspace{5px} F_1=1,\ F_2=1\\ (2)\ F_n={\large\frac{(1+\sqrt5)^n-(1-\sqrt5)^n}{2^n\sqrt5}}\\ [/Tex]
Python
# To find the n-th Fibonacci Number using formula
from math import sqrt
# import square-root method from math library
def nthFib(n):
res = (((1+sqrt(5))**n)-((1-sqrt(5)))**n)/(2**n*sqrt(5))
# compute the n-th fibonacci number
print(int(res),'is',str(n)+'th fibonacci number')
# format and print the number
# driver code
nthFib(12)
# This code is contributed by Kush Mehta
Output144 is 12th fibonacci number
Time Complexity: O(1)
Auxiliary Space: O(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.
Python
# Function for nth Fibonacci number
def Fibonacci(n):
if n<= 0:
print("Incorrect input")
# First Fibonacci number is 0
elif n == 1:
return 0
# Second Fibonacci number is 1
elif n == 2:
return 1
else:
return Fibonacci(n-1)+Fibonacci(n-2)
# Driver Program
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.
Python
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
# Driver Program
print(fibonacci(9))
Time Complexity: O(N)
Auxiliary Space: O(N)
Fibonacci number Using DP with Space Optimization
Here, Space Optimisation taking 1st two fibonacci numbers as 0 and 1.
Python
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
# Driver Program
print(fibonacci(9))
Time Complexity: O(N)
Auxiliary Space: O(1)
Python Program for n-th Fibonacci number Using Array
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.
Python
# creating an array in the function to find the
#nth number in fibonacci series. [0, 1, 1, ...]
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]
# Driver Program
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.
Get n-th Fibonacci Number Using Matrix
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]]
# n - 1 times multiply the
# matrix to {{1,0},{0,1}}
for i in range(2, n + 1):
multiply(F, M)
# Driver Code
if __name__ == "__main__":
n = 9
print(fib(n))
Time Complexity: O(n)
Auxiliary Space: O(1)
Optimization of Above Methods
We 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).
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
# Optimized version of
# power() in method 6
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)
# Driver Code
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!
Similar Reads
How to check if a given number is Fibonacci number?
Given a number ânâ, how to check if n is a Fibonacci number. First few Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, .. Examples :Input : 8Output : YesInput : 34Output : YesInput : 41Output : NoApproach 1:A simple way is to generate Fibonacci numbers until the generated number
15+ min read
Nth Fibonacci Number
Given a positive integer n, the task is to find the nth Fibonacci number. The Fibonacci sequence is a sequence where the next term is the sum of the previous two terms. The first two terms of the Fibonacci sequence are 0 followed by 1. The Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21 Example: Inp
15+ min read
C++ Program For Fibonacci Numbers
The Fibonacci series is the sequence where each number is the sum of the previous two numbers. The first two numbers of the Fibonacci series are 0 and 1 and are used to generate the whole series. In this article, we will learn how to find the nth Fibonacci number in C++. Examples Input: 5Output: 5Ex
5 min read
Python Program for n-th Fibonacci number
In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation Fn = Fn-1 + Fn-2With seed values F0 = 0 and F1 = 1.Table of Content Python Program for n-th Fibonacci number Using Formula Python Program for n-th Fibonacci number Using RecursionPython Program for n-th
6 min read
Interesting Programming facts about Fibonacci numbers
We know Fibonacci number, Fn = Fn-1 + Fn-2. First few Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, .... . Here are some interesting facts about Fibonacci number : 1. Pattern in Last digits of Fibonacci numbers : Last digits of first few Fibonacci Numbers ar
15+ min read
Find nth Fibonacci number using Golden ratio
Fibonacci series = 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ........Different methods to find nth Fibonacci number are already discussed. Another simple way of finding nth Fibonacci number is using golden ratio as Fibonacci numbers maintain approximate golden ratio till infinite. Golden ratio: [Tex]\varphi
6 min read
Fast Doubling method to find the Nth Fibonacci number
Given an integer N, the task is to find the N-th Fibonacci numbers.Examples: Input: N = 3 Output: 2 Explanation: F(1) = 1, F(2) = 1 F(3) = F(1) + F(2) = 2 Input: N = 6 Output: 8 Approach: The Matrix Exponentiation Method is already discussed before. The Doubling Method can be seen as an improvement
14 min read
Tail Recursion for Fibonacci
Write a tail recursive function for calculating the n-th Fibonacci number. Examples : Input : n = 4 Output : fib(4) = 3 Input : n = 9 Output : fib(9) = 34 Prerequisites : Tail Recursion, Fibonacci numbersA recursive function is tail recursive when the recursive call is the last thing executed by the
4 min read
Sum of Fibonacci Numbers
Given a number positive number n, find value of f0 + f1 + f2 + .... + fn where fi indicates i'th Fibonacci number. Remember that f0 = 0, f1 = 1, f2 = 1, f3 = 2, f4 = 3, f5 = 5, ... Examples : Input : n = 3Output : 4Explanation : 0 + 1 + 1 + 2 = 4 Input : n = 4Output : 7Explanation : 0 + 1 + 1 + 2 +
9 min read
Fibonacci Series
Program to Print Fibonacci Series
Ever wondered about the cool math behind the Fibonacci series? This simple pattern has a remarkable presence in nature, from the arrangement of leaves on plants to the spirals of seashells. We're diving into this Fibonacci Series sequence. It's not just math, it's in art, nature, and more! Let's dis
9 min read
Program to Print Fibonacci Series in Java
The Fibonacci series is a series of elements where the previous two elements are added to generate the next term. It starts with 0 and 1, for example, 0, 1, 1, 2, 3, and so on. We can mathematically represent it in the form of a function to generate the n'th Fibonacci number because it follows a con
6 min read
Print the Fibonacci sequence - Python
To print the Fibonacci sequence in Python, we need to generate a series of numbers where each number is the sum of the two preceding ones, starting from 0 and 1. The Fibonacci sequence follows a specific pattern that begins with 0 and 1, and every subsequent number is the sum of the two previous num
5 min read
C Program to Print Fibonacci Series
The Fibonacci series is the sequence where each number is the sum of the previous two numbers of the sequence. The first two numbers are 0 and 1 which are used to generate the whole series. Example Input: n = 5Output: 0 1 1 2 3Explanation: The first 5 terms of the Fibonacci series are 0, 1, 1, 2, 3.
4 min read
JavaScript Program to print Fibonacci Series
The Fibonacci sequence is the integer sequence where the first two terms are 0 and 1. After that, the next term is defined as the sum of the previous two terms. The recurrence relation defines the sequence Fn of Fibonacci numbers: Fn = Fn-1 + Fn-2 with seed values F0 = 0 and F1 = 1 Examples: Input :
4 min read
Length of longest subsequence of Fibonacci Numbers in an Array
Given an array arr containing non-negative integers, the task is to print the length of the longest subsequence of Fibonacci numbers in this array.Examples: Input: arr[] = { 3, 4, 11, 2, 9, 21 } Output: 3 Here, the subsequence is {3, 2, 21} and hence the answer is 3.Input: arr[] = { 6, 4, 10, 13, 9,
5 min read
Last digit of sum of numbers in the given range in the Fibonacci series
Given two non-negative integers M, N which signifies the range [M, N] where M ? N, the task is to find the last digit of the sum of FM + FM+1... + FN where FK is the Kth Fibonacci number in the Fibonacci series. 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ... Examples: Input: M = 3, N = 9 Output:
5 min read
K- Fibonacci series
Given integers 'K' and 'N', the task is to find the Nth term of the K-Fibonacci series. In K - Fibonacci series, the first 'K' terms will be '1' and after that every ith term of the series will be the sum of previous 'K' elements in the same series. Examples: Input: N = 4, K = 2 Output: 3 The K-Fibo
7 min read
Fibonacci Series in Bash
Prerequisite: Fibonacci Series Write a program to print the Fibonacci sequence up to nth digit using Bash. Examples: Input : 5 Output : Fibonacci Series is : 0 1 1 2 3 Input :4 Output : Fibonacci Series is : 0 1 1 2 The Fibonacci numbers are the numbers in the following integer sequence . 0, 1, 1, 2
1 min read
R Program to Print the Fibonacci Sequence
The Fibonacci sequence is a series of numbers in which each number (known as a Fibonacci number) is the sum of the two preceding ones. The sequence starts with 0 and 1, and then each subsequent number is the sum of the two previous numbers. The Fibonacci sequence has many applications in various fie
2 min read