26 Réponses
+ 1
Hi!
It is exactly what you wrote in your code, but start to calculate from start case:
Calculate F(3):
• (n = 0) => Fib(0) = n = 0 (start case)
• (n = 1) => Fib(1) = n = 1 (start case)
• (n = 2) => Fib(2) = Fib(n-1) + Fib(n-2) = Fib(1) + Fib(0) = 0 + 1 = 1 (the ’second’ 1)
• (n = 3) => Fib(3) = Fib(n-1) + Fib(n-2) = Fib(2) + Fib(1) = 1 + 1 = 2
• (n=4) => Fib(4) = Fib(n-1) + Fib(n-2) = Fib(3) + Fib(2) = 2 + 1 = 3
• (n =5) => Fib(5) = Fib(n-1) + Fib(n-2) = Fib(4) + Fib(3) = 3 + 2 = 5
Thus:
Fib(0) = 0
Fib(1) = 1
Fib(2) = 1
Fib(3) = 2
Fib(4) = 3
Fib(5) = 5
+ 1
just use this formula
fib(n) =fib(n-1) +fib(n-2)
And for base case
if n==1 or n==2
return 1
+ 1
if n==1 or n==2:
return 1
return fibonacci(n-1)+fibonacci(n-2)
+ 1
Ah print the output bro -_-
+ 1
Oh okay. I got that idea when I used the iterative method but with the recursive one.
The mistake I think I was doing was adding it straight from the return without considering the ones gotten already .
Thank you.
+ 1
Yes, if you are happy, I am too.
0
It's not working
0
Show me your code after my line
0
num = int(input())
def fibonacci(n):
if n <= 1:
return 0
else:
return fibonacci(n-1) + fibonacci(n+2)
fibonacci(num)
0
Try it and see, that's my code
https://code.sololearn.com/cAmndo0LuGv0/?ref=app
0
Okay bro
I have done that but it only prints one number
0
What you want to print whole series upto n??
0
I want to print the Fibonacci sequence of numbers of n.
0
I recommend do it using for loop
0
Okay
Thank you , I was able to do it but I need more explanation on this code:
https://code.sololearn.com/cAmndo0LuGv0/?ref=app
0
What explaination you want??
0
When I break the code down, I don't get understand how the 1's came twice but when I use the iterative code to find for the Fibonacci sequence, I understand it over there.
0
But when you use range, it better use (num + 1) instead of just num. Otherwise you print all fibonacci up to n-1, but not fibonacci(n).
for n in range(num + 1):
print(fibonacci(n))
0
Okay, let me try that one too
0
I just tried that and I saw no difference from the other one.