+ 1
good afternoon, I have this java problem, can you help me?
static long fib(int n){ if (n <= 1) return n; return fib(n-1) + fib(n-2); } write a program that calculates the nth fibonacci number (fib (n)) simulating the recursive invocation of the above function using a stack
10 Answers
+ 1
Maybe like this one:
https://code.sololearn.com/c2M3zREGsTTo/?ref=app
+ 1
Maybe missing curly braces in the if statement
static long fib(int n){
if (n<=1){
return n;
}
return fib(n-1)+fib(n-2);
}
https://code.sololearn.com/c2M3zREGsTTo/?ref=app
0
Mention what is the problem with that code.. Better to post full code..
0
thanks thomas, with that implementation you already solved my question? I mean, the thing about the invocation through a stack
0
Not sure what you mean, recursion by default uses a stack, seeing a stackoverflow error in this endless recursion proves that
https://code.sololearn.com/cv71c0aHv5Ip/?ref=app
0
Now this code is good to get the right number. But it is recursive. I thing your task is to simulate this with using a Stack?
0
exactly Thomas I must simulate that using a stack, can you help me?
0
Here a solution w/o recursion. But also no full Stack. Only the both just needed values are in f[0] and f[1]
https://code.sololearn.com/c6J3xOT07b15/?ref=app
0
Create an array with n elements.
Set the first 2 elements with 0 and 1.
Then the Element
array[2] = array[1] + array[0]
array[3] = array[2] + array[1]
And so on, up to the last field.
array[n] = array[n-1] + array[n-2]
I think that's easy, and all values are in a Stack / Array.
0
Thanks