The **Fibonacci Sequence** is the series of numbers:

$0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...$

The series starts with $0$ and $1$ as the first two numbers in the series. The next number in the series is found by summing the two numbers before it.

For example:

- The third number in the sequence, $1$, is found by adding the two numbers before it $(0+1)$.
- The fourth number in the sequence, $2$, is found by adding the two numbers before it $(1+1)$.

Fibonacci Sequence can be implemented both iteratively and recursively in Python.

For both examples, try changing the value of the argument passed to the function to print out more numbers in the sequence.

def fib(number_of_terms):counter = 0first = 0second = 1temp = 0while counter <= number_of_terms:print(first)temp = first + secondfirst = secondsecond = tempcounter = counter + 1# Driver Codefib(10)

In the above implementation, The code prints the `first`

value on each iteration of the loop. Each iteration calculates the next value by summing the previous two values and then updates the values of `first`

and `second`

. The time complexity of the above iterative implementation is $O(n)$.

Calculating the 6th Fibonacci number.

def fib(term):if term <= 1:return (term)else:return (fib(term-1) + fib(term-2))# Change this value to adjust the number of terms in the sequence.number_of_terms = 10for i in range(number_of_terms):print(fib(i))

The above program computes the Fibonacci value by calling itself with a lesser value several times. The termination condition for this is reached when `term == 0`

and `term == 1`

. The time complexity for this solution is $O(2^n)$.

Copyright Â©2024 Educative, Inc. All rights reserved

TRENDING TOPICS