Here is how to Calculate Fibonacci using Recursive Function and Iterative Method in Python. Recursive method here is very expensive in terms of processing. For a larger number, it will hang the device.
Run the code here: https://repl.it/@VinitKhandelwal/fibonacci
21
Run the code here: https://repl.it/@VinitKhandelwal/fibonacci
# Recursive - O(2^n)
def fibonacciRecursive(n):
if n < 2:
return n
return fibonacciRecursive(n-1) + fibonacciRecursive(n-2)
# Iterative - O(n)
def fibonacciIterative(n):
result = 0
now = 1
for i in range(1, n+1):
prev = now
now = result
result = prev + now
return result
print(fibonacciRecursive(8))
print(fibonacciIterative(8))
OUTPUT
2121
Comments
Post a Comment