Fibonacci sequence in python

Fibonacci sequence in python 

Sequence is 

0    1    1    2    3    5    8    13    21    34    55    89

every no is a sum of past 2 no's 

1st & 2nd no would be 0 & 1 respectively 

  • 3rd no(c) = 1st(a) + 2nd(b)
    3rd no = 0 +1 = 1
    Sequence would be 0    1    1

  • 4th no = 2nd + 3rd
    4th no = 1 +1 = 2
    Sequence would be 0    1    1    2

  • 5th no = 3rd + 4th
    5th no = 1 +2 = 3
    Sequence would be 0    1    1    2    3

Similarly , the sequence continues

Code Explanation 

Consider 3 variables a, b, c

a, b ,c would be 1st , 2nd & 3rd no respectively

set a =0 b=1 and c= a + b

for each iteration swap the values as

a would have value of  b 

b would have value of  c


Iteration 1 :- a=0 b=1 c=a +  b

  • 3rd no(c) = 1st(a) + 2nd(b)
    3rd no(c) = 0 +1 = 1
    Sequence would be 0    1    1

Iteration 2 :- a=1 b=1 c=a + b

  • 4th no(c) = 2nd(a) + 3rd(b)
    4th no = 1 +1 = 2
    Sequence would be 0    1    1    2

Iteration 3 :- a=1 b=2 c=a + b

  • 5th no = 3rd + 4th
    5th no = 1 +2 = 3
    Sequence would be 0    1    1    2    3





Code:- 


#fibonacci sequence
n=int(input("No of elements in the sequence"))
a,b = 0,1 
print(a,b,end=" ")
for i in range(n-2):
    c=a+b 
    print(c,end=" ")
    a,b=b,c

Run The Code

Post a Comment

0 Comments