Finding fibonacci series with python!

  • 08-12-2017
  • python
Thumb

Share:

https://techconductor.com/blogs/python/finding_fibonache_series.php

Copy

Fibonacci series is one of the most interesting series in Mathematics and can be widely observed in many places specially in the nature. The Fibonacci series is named after Italian mathematician Leonardo of Pisa, known as Fibonacci.

Fibonacci series begins with 1, 1 and the keeps on ading the previous two digits like 1 + 1 is 2 and 1 + 2 is 3 and 2 + 3 is 5 and so on the series become 1, 1, 2, 3, 5, 8, 13, 21,...

So to find the series in python we can use 2 ways one is to use the recursion function and another is to use a loop to do the job. You can think recursion as a function that repeats itself but its not like the loop.

Let's first see how to use recursion to find the series, here is how it looks.


Coudn't load the image

Here we defined a function fib1 which takes one argument n which is the length of the series we want to find. Line-2 is the condition when n is 1 or 2 the function simply returns 1. Line-5 is the main recursion formula it calls itself or the function fib1 and gives the argument n-1 and waits for it to return a value and adds it to the returned value of another recursion of n-2 which again does the same process.

Well the recursion does works but crunch up lots of memory and processing power. It takes 2-3 seconds just find to find the 10 places of the series.

Now let's take a look at the another method using a for loop. Here is how it looks.


Coudn't load the image

Here we again defined a function fib2 which takes a argument n. Line-3 here variables a and b are both assigned a value 1 next on Line-4 is the for loop which assigns a the value of b and to b assigns a valus of a + b. Then it simply returns the value of a.

On Line-8 here we are using the main loop which provides the argument for the fib2 function and prints the returned value. Here we just set the range to 1, 100 which means we are finding the series from 1 to 100 digits or length.

But the difference is that using the for loop to find the series is way much faster and memory efficient then using the recursion to do the same.

Reference: Fibonacci number Recursion(Computer Science)