+ 7

Challenge question in Java about recursion

I found this question in Java challenge really strange. It's about recursion obviously, but after x becomes 100, I don't understand what happen next and how the answer is 95. If someone can explain I'll be grateful. https://code.sololearn.com/c1Ss5wKJvyPU/?ref=app

8th Jan 2020, 8:48 PM
TheWh¡teCat 🇧🇬
TheWh¡teCat 🇧🇬 - avatar
10 Respuestas
+ 8
TheWh¡teCat 🇧🇬 f(60) calls f(70) calls f(80) calls f(90) calls f(100) Each function call goes into a stack: f(90) f(80) f(70) f(60) f(100) returns 99 f(90) gets 99 from f(100) and returns 99 - 1 f(80) gets 98 from f(90) and returns 98 - 1 f(70) gets 97 from f(80) and returns 97 - 1 f(60) gets 96 from f(70) and returns 96 - 1 stack is empty -> output: 95
9th Jan 2020, 4:26 PM
Denise Roßberg
Denise Roßberg - avatar
+ 7
It's quite tricky, but it becomes easier to understand once you've written it down. f(60) = f(60+10) - 1 // f(70) - 1 = f(70+10) - 1 - 1 // f(80) - 2 = f(80+10) - 2 - 1 // f(90) - 3 = f(90) - 3 - 1 // f(100) - 4 = (100 - 1) - 4 = 95.
8th Jan 2020, 9:20 PM
Diego
Diego - avatar
+ 5
TheWh¡teCat 🇧🇬 Sankalp👨‍💻👨‍💻 Yes. You can imagine a stack like a glass: the stuff which goes as first into stack is at the bottom. |3| |2| |1| When you want to empty a stack, its starts at 3. then 2, then 1. -> LIFO last in, first out I added some print statements to your code: https://code.sololearn.com/ckFHWmZcXhQK/?ref=app Edit: about stacks https://www.sololearn.com/learn/642/?ref=app
9th Jan 2020, 4:52 PM
Denise Roßberg
Denise Roßberg - avatar
+ 3
Thanks a lot for the explanation Denise Roßberg , I think that solves the problem 🐱
9th Jan 2020, 4:40 PM
TheWh¡teCat 🇧🇬
TheWh¡teCat 🇧🇬 - avatar
+ 3
Sankalp👨‍💻👨‍💻 , the exact explanation. I was debugging it few days ago and I was confused with the things I saw => on one hand the current argument of the method and next what returns the method five times 99, 80, 98, 70 and I didn't find the logic in this sequence. Now everything is clear 🐱
9th Jan 2020, 4:49 PM
TheWh¡teCat 🇧🇬
TheWh¡teCat 🇧🇬 - avatar
+ 3
Thanks again for the detailed explanation, Denise Roßberg 🐱
9th Jan 2020, 6:12 PM
TheWh¡teCat 🇧🇬
TheWh¡teCat 🇧🇬 - avatar
+ 2
Thanks for the effort Diego, but it doesn't seem to work in that pattern. I tried to debug it some days ago and if I remember it right (I'll check it again later) the recursion repeats until x becomes 100, then x is 99 (x - 1), but after that I just can't understand what happen - x becomes 88, next 70 and the next steps I don't remember.
9th Jan 2020, 10:13 AM
TheWh¡teCat 🇧🇬
TheWh¡teCat 🇧🇬 - avatar
0
TheWh¡teCat 🇧🇬 Your welcome :)
9th Jan 2020, 6:22 PM
Denise Roßberg
Denise Roßberg - avatar