How to find the nth Fibonacci number in Python
There are several methods to find the nth Fibonacci number in Python. These are as follows:
- Using recursion
- Using dynamic programming
- Using dynamic programming and space optimization
- Using arrays
Of these methods, the two most basic are the Dynamic method and recursion.
Let’s take a deeper look at how each of these methods works.
1. Using recursion
Recursion defines something within itself. In Python, recursion refers to the process of a function calling itself. With the correct code recursion will create a finite loop.
In the code below:
- We are aware that the first two Fibonacci numbers are
0&1. - In the event of the input as
n=1orn=2(1st or 2nd Fibonacci numbers), we use an if-else statement to return0or1. - If
nis greater than2, The function calls itself with a lower input value. As you see in the code, it returns(fibonacci(n-1)+fibonacci(n-2)). - Here, the function calls itself with a lower value until it reaches the base value of
n=1andn=2, and as we know from before,n=1returns0andn=2returns1. - The returned values are then continuously added to produce the sequence of the Fibonacci series.
def Fibonacci(n):if n<0:print("Incorrect input")# First Fibonacci number is 0elif n==0:return (0)# Second Fibonacci number is 1elif n==1:return (1)else:return (Fibonacci(n-1)+Fibonacci(n-2))print(Fibonacci(10))
2. Using dynamic programming
Dynamic programming uses recursion too, but it mainly uses if-else statements. In the statements, a variable is used to store the value of the Fibonacci number. This Fibonacci number is obtained by repeated addition which is obtained using recursion. In the given program, the storage variable is named ‘x’.
In the code below:
- We start with a one-dimensional array; the
FibArraywith elements0&1in its .0th and 1st indices being 0&1 - Then, if the given input (’n’) is less than or equal to
2(i.e., the length of the arrayFibArray), it returns0as the first number (n=1) and1as the second number (n=2). - If
nis greater than2, we use recursion to call and add the previous 2 elements (similar to the first code). - However, here, instead of returning the nth Fibonacci number directly, we append each of the summated elements to the
FibArrayarray. Finally, we return the last element of the array (the nth element).
def fibonacci(n):# Taking 1st two fibonacci nubers as 0 and 1fibArray = [0, 1]# Here, since we know that the first 2 fibonacci numbers are 0 and 1, we append the remaining values (Fibonacci numbers from index 2 to n) in the array using recursion and return the last element.# In the range function, we take range(2,n+1) instead of range(2,n). This is because range function in python iterates until the value before the upper limit. So, if we take from 2 to n, it would only iterate from 2nd to (n-1)th element.for i in range(2, n+1):fibArray.append(fibArray[i-1] + fibArray[i-2])return fibArray[n]print(fibonacci(10))
3. Using dynamic programming and space optimization
This method is almost entirely the same as dynamic programming. However, dynamic programming uses recursion to achieve repeated addition, while this method uses the `for loop’.
In the code below:
- We take 2 pre-assigned variables
a=0andb=1– they are the 1st & 2nd elements of the series. - Then, we return
0for input valuen=1and1for input valuen=2using if-else statements. Ifnis greater than2, we take a ‘for’ loop ofiin range( 2,n). This range function means the loop starts with the value2and keeps iterating until the valuen-1. - Over here, we take a storage variable
c. This variable is used to store the sum of the previous two elements in the series. - Consider the series to be quite literally in the sequence of a, b, & c. Once
ctakes the value ofa+b, the value ofais reassigned tob. Subsequently, the value ofbis reassigned to the value ofc. To put it more simply, aftercbecomesa+b,a = bandb = c. - This process continues and value 3 keeps reassigning until the loop terminates.
- Once the loop is terminated, the function returns the value of
b, which stores the value of the nth Fibonacci number.
# Similar to previous example, we take first 2 fibonacci numbers as 0 and 1.def fibonacci(n):a = 0b = 1if n < 0:print("Incorrect input")elif n == 0:return aelif n == 1:return b# In the previous example, 'recursion' was used to create a finite loop. Over her, we use a for loop insted in order to obtain the fibonacci series.else:for i in range(2,n+1):c = a + ba = bb = creturn bprint(fibonacci(10))
4. Using arrays
In this method, an array of size n is created by repeated addition using the for loop. Then, the nth element is returned.
In the code below:
-
We start by creating an array
FibArrayof sizen+1– This is because, when we say nth Fibonacci number’, we start counting from1. But, the index of an array starts from0. Hence, we give an additional space because the nth Fibonacci number will have the index value n+1. -
At the creation of the array, all values are ‘0’ by default. Hence, we leave the 1st number (index 0) and change the 2nd number (index 1) to the value
1. -
Now, we take a
for loopwith the variableiin range(2,n+1). As explained in the previous code, the loop will start with the valuei=2and end with the valuei=n. -
Next, in the loop, we assign the value of each element of the array. The
i-thelement’s value is equal to the sum of the previous two elements in that array. -
As the loop iterates, each value of the array is filled.
-
Finally, after the loop terminates, the value with index
n-1is returned.
As explained before, The array index value starts from
0, but we start counting from1. Hence, when we say ’nth Fibonacci number’ or ’nth element of the array’, the element holds the index valuen-1. So, we return then-1index element instead of thenindex element.
def fibonacci (n):#creating an array in the function to find the nth number in fibonacci series. [0,1,1,...]FibArray = [0] * (n+1)FibArray[1] = 1#Over here, we are adding elements of the series to the array using addition of provious 2 elements.for i in range (2,n+1):FibArray[i] = FibArray[i-1] + FibArray[i-2]return FibArray[n]if __name__ == "__main__":print(fibonacci (10))