+ 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

28th Sep 2020, 7:41 PM
Juan pablo Peña
Juan pablo Peña - avatar
10 Réponses
29th Sep 2020, 7:54 AM
Coding Cat
Coding Cat - avatar
+ 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
28th Sep 2020, 8:41 PM
Coding Cat
Coding Cat - avatar
0
Mention what is the problem with that code.. Better to post full code..
28th Sep 2020, 8:23 PM
Jayakrishna 🇮🇳
0
thanks thomas, with that implementation you already solved my question? I mean, the thing about the invocation through a stack
28th Sep 2020, 8:53 PM
Juan pablo Peña
Juan pablo Peña - avatar
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
28th Sep 2020, 8:57 PM
Odyel
Odyel - avatar
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?
28th Sep 2020, 8:58 PM
Coding Cat
Coding Cat - avatar
0
exactly Thomas I must simulate that using a stack, can you help me?
28th Sep 2020, 9:01 PM
Juan pablo Peña
Juan pablo Peña - avatar
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
28th Sep 2020, 9:03 PM
Coding Cat
Coding Cat - avatar
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.
28th Sep 2020, 9:15 PM
Coding Cat
Coding Cat - avatar
0
Thanks
29th Sep 2020, 7:56 AM
Juan pablo Peña
Juan pablo Peña - avatar