Skip to main content

Fibonacci Series in Python | Algorithm, Codes, and more

 

 It is a sequence of integers 0, 1, 1, 2, 3, 5... The series starts with 0 and 1. All other terms are obtained by adding the last two numbers of the sequence, i.e., to get the nth number, sum the (n-1)th and (n-2)th number. 

It is a series of numbers that starts from 0 and 1 and then continues by adding the preceding two numbers. 

In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the function, 

 Fn = Fn-1 + Fn-2

With the initial two terms' values,

 F0 = 0 and F1 = 1


 

Different Methods to print Fibonacci Series in Python are:

  • Method 1: Using Recursion

  • Method 2: Using Dynamic Programming

  • Method 3: Using While Loop

Method 1: Using Recursion

Recursion is the primary programming technique in which a function or algorithm calls itself directly or indirectly until a specified condition is met. Let’s see how to use recursion to print the first ‘n’ numbers of the Fibonacci Series in Python.

The function “fibonacciSeries” is called recursively until we get the output. We first check whether the Number is zero or one in the function. If yes, we return the value of the Number. If not, we recursively call Fibonacci with the values Number-1 and Number-2.

Implementation

#Python program to generate Fibonacci series Program using Recursion

def fibonacciSeries(Number):

    if(Number == 0):

        return 0

    elif(Number == 1):

        return 1

    else:

        return (fibonacciSeries(Number - 1) + fibonacciSeries(Number - 2))



n = int(input())

print("Fibonacci series:", end = ' ')

for n in range(0, n):  

   print(fibonacciSeries(n), end = ' ')

 

Input:

6

Output:

Fibonacci Series: 0 1 1 2 3 5

Recurrence Relation = T(n) = T(n-1) + T(n-2).

Time complexity 

The time complexity for this program is O(2n)

Space complexity

The space complexity for this program is O(n)

 

Method 2: Using Dynamic Programming

We can also use Dynamic Programming to print the Fibonacci Series in python. The first two fixed values of the Fibonacci series are 0 and 1. We start our loop from the second index and try to append the values in the loop using the previous two numbers.

Implementation

#fibonacci series in python using dynamic programming

def fibonacci(n):

# Taking 1st two fibonacci numbers as 0 and 1

f = [0, 1]

for i in range(2, n+1):

f.append(f[i-1] + f[i-2])

return f

n = int(input())

ans=fibonacci(n)

for n in range(0, n):

  print(ans[n], end = ' ')

Input:

Enter the value of 'n': 5

Output:

0 1 1 2 3

Time complexity 

The time complexity for this program is O(n)

Space complexity

The space complexity for this program is O(n)

 

Method 3: Using While Loop

The last approach we will be discussing is using a while loop. We will use some basic conditions to print the Fibonacci series. As we already know, the first two numbers of the Fibonacci series are 0 and 1 by default. Input the number of values we want to generate the Fibonacci sequence and initialize a=0, b=1, sum=0, and count=1. Start a while loop using the condition count<=n and print the sum every time the condition works. Increment the count variable, swap ‘a’ and ‘b,’ and store the addition of a and b in the sum. If count>n, the condition fails, and the algorithm ends.

Implementation

#Python program to generate Fibonacci series based on n value



n = int(input())

a = 0

b = 1

sum = 0

count = 1

print("Fibonacci series is: ", end = " ")

while(count <= n):

  count += 1

  print(a, end=" ")

  a = b

  b = sum

  sum = a + b

Input:

3

Output:

Fibonacci Series:  0 1 1

Time complexity 

The time complexity for this program is O(n)

Space complexity

The space complexity for this program is O(1)

You can practice by yourself with the help of online python compiler.

Frequently Asked Questions

What is the Fibonacci series in Python?

It is a sequence of integers 0, 1, 1, 2, 3, 5... The series starts with 0 and 1. All other terms are obtained by adding the last two numbers of the sequence, i.e., to get the nth number, sum the (n-1)th and (n-2)th number.

How do you write a Fibonacci series in Python?

You can write a Fibonacci series in Python through multiple methods, such as recursion, dynamic programming, and a while loop or For loop. First, define the base case for the first two values, 0 and 1. Then, add the last two values, and you will get the next integer in sequence.

How do you find the nth Fibonacci number in Python?

A Fibonacci series starts with 0 and 1. The later numbers are generated by adding the previous two values of the series. If n is 1 or 2, the answer would be 0 and 1, respectively. Otherwise, keep adding the last two Fibonacci numbers until you get the nth number.

Conclusion

This article discusses the different approaches to finding the Nth Fibonacci sequence using Python.

The different approaches we used are below:

  1. Recursion

  2. Dynamic Programming

  3. While Loops

Important Links

Home Page 

Courses Link  

  1. Python Course  

  2. Machine Learning Course 

  3. Data Science Course 

  4. Digital Marketing Course  

  5. Python Training in Noida 

  6. ML Training in Noida 

  7. DS Training in Noida 

  8. Digital Marketing Training in Noida 

  9. Winter Training 

  10. DS Training in Bangalore 

  11. DS Training in Hyderabad  

  12. DS Training in Pune 

  13. DS Training in Chandigarh/Mohali 

  14. Python Training in Chandigarh/Mohali 

  15. DS Certification Course 

  16. DS Training in Lucknow 

  17. Machine Learning Certification Course 

  18. Data Science Training Institute in Noida

  19. Business Analyst Certification Course 

  20. DS Training in USA 

  21. Python Certification Course 

  22. Digital Marketing Training in Bangalore

  23. Internship Training in Noida

  24. ONLEI Technologies India

  25. Python Certification

  26. Best Data Science Course Training in Indore

  27. Best Data Science Course Training in Vijayawada

  28. Best Data Science Course Training in Chennai

  29. ONLEI Group

  




Comments

Popular posts from this blog

Data Science Career Path: Learn & Land Your Job

  Embarking on a career in data science offers a world of possibilities in today's technology-driven landscape. As the demand for skilled data professionals continues to soar, it becomes increasingly vital to equip oneself with the necessary knowledge and expertise to thrive in this field. ONLEI Technologies stands out as a beacon of opportunity, offering comprehensive live online training programs designed to prepare aspiring data scientists for success. In this article, we delve into the intricacies of the data science career path, highlighting the importance of live online training, exploring ONLEI Technologies' innovative training program, and providing insights into key skills and strategies essential for securing a rewarding data science job. Introduction to Data Science Career Path Ah, data science, the cool kid on the career block! If you're a fan of numbers, patterns, and unraveling mysteries hidden in heaps of data, then this might just be the wand you need to wa...

Machine Learning Techniques

Machine learning is a data analytics technique that teaches computers to do what comes naturally to humans and animals: learn from experience. Machine learning algorithms use computational methods to directly "learn" from data without relying on a predetermined equation as a model. As the number of samples available for learning increases, the algorithm adapts to improve performance. Deep learning is a special form of machine learning . How does machine learning work ? Machine learning uses two techniques: supervised learning, which trains a model on known input and output data to predict future outputs, and unsupervised learning, which uses hidden patterns or internal structures in the input data. Supervised learning Supervised machine learning creates a model that makes predictions based on evidence in the presence of uncertainty. A supervised learning algorithm takes a known set of input data and known responses to the data (output) and trains a model to generate reason...

Marketing Strategy of Cadbury

  Marketing Strategy of Cadbury  The marketing strategy of Cadbury has helped the brand create such a place in the hearts of Indian customers that the first thing that comes to our minds when someone says “chocolate” is “Cadbury”. A certain class of Indians does not even say the word “ chocolate ”, they’d say “Would you like to have a Cadbury?” Such has been the influence of Cadbury on its consumers’ minds. About Cadbury India Cadbury was established by John Cadbury in 1824 in Birmingham, England. Later, In 2010, it was acquired by Kraft Foods and is currently managed by Mondelez International. Cadbury India was established in 1948 in India and is currently headquartered in Mumbai, Maharashtra. Its headquarters in Mumbai is popularly also called “Cadbury House”. At present, Cadbury India operates in five categories – chocolate confectionery, beverages, and biscuits. Its popular products include Dairy Milk, Oreo, Tang, Bournvita, etc. The company has also tied up with Hindus...