If we find higher fibonaci no (like 40) by recursion it takes a long time . why? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

If we find higher fibonaci no (like 40) by recursion it takes a long time . why?

code is def fib(n): if(n<2): return 1 else: return fib(n-1)+fib(n-2)

29th Nov 2016, 4:09 PM
Adithya Anand
Adithya Anand - avatar
12 Answers
+ 3
yeah, that's exactly what i say ;) good luck
29th Nov 2016, 8:05 PM
Nima Moradi
Nima Moradi - avatar
+ 2
@donkeyhot we calculate all of the previous members of the fibonacci sequence, but we just do it once each time, while the reqursive mode of this algorithm calculate some operations more than this dp algorithm that i say
29th Nov 2016, 7:13 PM
Nima Moradi
Nima Moradi - avatar
+ 2
Ok, i get it. I thought python interpreter is smart enough to store previously calculated values. https://code.sololearn.com/cVvnJBqQ6FNx/#py
29th Nov 2016, 8:02 PM
donkeyhot
donkeyhot - avatar
+ 2
http://www.python-course.eu/recursive_functions.php
29th Nov 2016, 8:04 PM
donkeyhot
donkeyhot - avatar
+ 1
well, in recursion mode you calculate some fib(x) that actually you don't need them. hence for example you should use a dp(dynamic programming) mode for compute the fibonacci instead of the divide and conquer mode, that is faster much more!
29th Nov 2016, 4:18 PM
Nima Moradi
Nima Moradi - avatar
+ 1
if we start to calculate the fibs from first member of fibonacci sequence, we just need the fib(n-1) and fib(n-2) to find fib(n) so we don't need the other fib members
29th Nov 2016, 4:39 PM
Nima Moradi
Nima Moradi - avatar
+ 1
@donkeyhot - I added a comment to your code with a generator function (to store previously generated values; using in-place swapping). It's not recursive (so OT) but may still be useful.
3rd Dec 2016, 12:48 PM
Kirk Schafer
Kirk Schafer - avatar
+ 1
@donkeyhot - open your code and then tap "1 comment" all the way over on the top right.
3rd Dec 2016, 12:59 PM
Kirk Schafer
Kirk Schafer - avatar
0
@Nima, how are you going to calculate fib(n) without knowing all the previous fib(1) ... fib(n-1)?
29th Nov 2016, 4:32 PM
donkeyhot
donkeyhot - avatar
0
And how would you know what fib(n-1) and fib(n-2) is without calculating the previous ones?
29th Nov 2016, 7:08 PM
donkeyhot
donkeyhot - avatar
0
@Kirk Schafer Where can I find this comment? Sorry for being a noob. I saw a notification, but when i tap on it nothing happens.
3rd Dec 2016, 12:56 PM
donkeyhot
donkeyhot - avatar
0
giving fibonaci as an example for recursion is...well, a really bad example. You should never use recursion for fib
19th Dec 2016, 1:48 PM
Stanislav Stoychev
Stanislav Stoychev - avatar