0

Anyone mind explaining this js problem?

function fib(num){ if(num<=2) return 1; return fib(num-1)+fib(num-2); } document.write(fib(6)); I just can't wrap my head around this one. I don't see how were getting an answer of 8. What do I need to know to be able to understand it?

30th Oct 2018, 2:15 AM
Spud
Spud - avatar
2 Respuestas
+ 7
function fib(num){ if(num<=2) return 1; return fib(num-1)+fib(num-2); } document.write(fib(6)); => The function is called with num = 6 and it returns fib(5) + fib(4) fib(5) returns fib(4) + fib(3) fib(4) returns fib(3) + fib(2) fib(3) returns 1 + 1 = 2 fib(2) returns 1 ........ fib(4) = 2+1= 3 fib(5) = 3+2 = 5 Similarly, fib(6) = fib(5) + fib(4) = 5 + 3 = 8
30th Oct 2018, 2:34 AM
Nikhil
Nikhil - avatar
+ 1
thanks very much for a great explanation
30th Oct 2018, 6:40 AM
Spud
Spud - avatar