+ 1

Confusing Recursion Quiz - Different print in emulator than answer.

The quiz says the answer should print 5 for returning 1 but when I run it I get 4. when I return 2 it will print 5 and when I return 3 it prints 6. when I do it on paper and show my work and return 1 I get 5. what am I doing wrong? https://code.sololearn.com/cp497z8PCrSp/?ref=app https://code.sololearn.com/cjVco29jwSQ6/?ref=app

3rd Jun 2017, 6:31 PM
Katelyn Eileen
Katelyn Eileen - avatar
2 ответов
+ 1
Your first link: Try using "return fib(x-1)+fib(x-2)" in your else (line 6). Instead of "return fib(x-1)+(x-2)". Now, if you print fib(4), it will return fib(3)+(4-2). The fib(3) will be recurrenced to fib(2)+(3-2). And so on till your get to your fib(1) in your if. The Fibonacci Sequence is defined by F(n)=F(n-1)+F(n-2). This is what happens now: print fib(4) returns fib(3)+(4-2) => returns (fib(2)+(3-2))+(4-2) => returns ((fib(1)+(2-2))+(3-2))+(4-2) => returns ((1)+(0))+(1))+(2) => returns 4 Your second link: Same problem in line 6, as explained above. And another problem in line 3: about the Fibonacci sequence itself. The first two numbers in the Fibonacci sequence are 1 and 1 (or 0 and 1, but that's more math preference) and each subsequent number is the sum of the previous two. So it looks like this: 1,1,2,3,5,8,13,21,34,... x is the position in the sequence. So the zero-th and the first position should be 1. Thus line 3 should be "return 1" instead of "return 2". I hope this clarifies a bit. :)
4th Jun 2017, 10:47 AM
Katarina_Cat
0
# 4 3 2 2 1 1 0 1 0 I take some time ,too. if you split it, you can find there are total five base cases(0 or 1).
18th Jun 2017, 10:13 AM
梁雪霖(黑心巧克力)
梁雪霖(黑心巧克力) - avatar