In this tutorial, we’ll learn how to write the Fibonacci series in python using multiple methods. The Fibonacci series is a series of numbers named after the Italian mathematician, called Fibonacci. A Fibonacci number is characterized by the recurrence relation given under:
Fn = Fn-1 + Fn-2
With F0 = 0 and F1 = 1.
We’ll be covering the following topics in this tutorial:
What is Fibonacci Series?
The first two numbers of a Fibonacci series are 0 and 1. The rest of the numbers are obtained by the sum of the previous two numbers in the series. It means to say the nth digit is the sum of (n-1)th and (n-2)th digit. In mathematical terms, the sequence Fn of all Fibonacci numbers is defined by the recurrence relation.
Fibonacci Series Formula
Therefore, the formula for calculating the series Would Be as follows:
xn = xn-1 + xn-2 ; where
xn is term number "n"
xn-1 is the previous digit (n-1)
xn-2 is the term before that
Example of Fibonacci Series: 0, 1, 1, 2, 3, 5
In the above example, 0 and 1 will be the first two digits of the series. The Logic of the Fibonacci Series to calculate the next digit by adding the first two digits. In this case, 0 and 1. Therefore, we get 0 + 1 = 1. Hence 1 is printed as the third digit. The following digit is generated by using the second and third digits rather than using the initial digit. It’s done until the number of terms you want or requested by the user.
Algorithm for printing Fibonacci series using a while loop
Step 1: Input the 'n' value Step 2: Initialize sum = 0, a = 0, b = 1 and count = 1 Step 3: while (count <= n) Step 4: print sum Step 5: Increment the count variable Step 6: swap a and b Step 7: sum = a + b Step 8: while (count > n) Step 9: End the algorithm Step 10: Else Step 11: Repeat from steps 4 to 7
Implementing the Fibonacci Series program in python
Fibonacci Sequence can be implemented both iteratively and recursively in Python.
#python program for fibonacci series until 'n' value n = int(input("Enter the value of 'n': ")) a = 0 b = 1 sum = 0 count = 1 print("Fibonacci Series: ", end = " ") while(count <= n): print(sum, end = " ") count += 1 a = b b = sum sum = a + b
Recursive function algorithm for printing Fibonacci series
Step 1:If 'n' value is 0, return 0 Step 2:Else, if 'n' value is 1, return 1 Step 3:Else, recursively call the recursive function for the value (n - 2) + (n - 1)
Python Program to Print Fibonacci Series until ‘n’ value using recursion
def fib(digit): if digit <= 1: return (digit) else: return (fib(digit-1) + fib(digit-2)) number_of_digit = 5 for i in range(number_of_digit): print(fib(i))