The Fibonacci Sequence is the series of numbers:
The series starts with and as the first two numbers in the series. The next number in the series is found by summing the two numbers before it.
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 = 0 first = 0 second = 1 temp = 0 while counter <= number_of_terms: print(first) temp = first + second first = second second = temp counter = counter + 1 # Driver Code fib(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
second. The time complexity of the above iterative implementation is .
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 = 10 for 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 .
View all Courses