Even with memoization I can not calculate the fibonacci (1000). This is my code (its same as a textbook example on memoization).
inputnumber = 10000 # the error starts if n > 998
existingvalues = {}
def fib_series(n):
if(n <= 1):
return n
else:
if(n in existingvalues):
value = existingvalues[n]
else:
value = fib_series(n-1) + fib_series(n-2)
existingvalues[n] = value
return value
the error I get:
Traceback (most recent call last):
File "C:/PycharmProjects/learnpy/11 - recursion.py", line 24, in <module>
print(fib_series(inputnumber))
File "C:/PycharmProjects/learnpy/11 - recursion.py", line 18, in fib_series
value = fib_series(n-1) + fib_series(n-2)
File "C:/PycharmProjects/learnpy/11 - recursion.py", line 18, in fib_series
value = fib_series(n-1) + fib_series(n-2)
File "C:/PycharmProjects/learnpy/11 - recursion.py", line 18, in fib_series
value = fib_series(n-1) + fib_series(n-2)
[Previous line repeated 994 more times]
File "C:/PycharmProjects/learnpy/11 - recursion.py", line 12, in fib_series
if(n <= 1):
RecursionError: maximum recursion depth exceeded in comparison
The reason why I wanted to do this, is comparing the performance between recursion and iteration. the following code does the iteration and can find the fibonacci for n > 1000 in almost similar time.
def fib_series(i):
a = 0
b = 1
c = 0
count = 0
while (count < i):
c = a + b
a = b
b = c
count = count + 1
print(c)
Is there anything related to O(complexity) that I should consider while comparing these two technique of addition (recursion vs iteration)?