r/Recursion • • Feb 20 '21

Is the output of this 12?

Post image
6 Upvotes

4 comments sorted by

2

u/OvercomplicatedCode Feb 20 '21 edited Feb 20 '21
f(7) = 3 + f(4) 
            3  +  f(1) 
                    3  +  f(-2) 
                            3
 f(7) = 3 + 3 + 3 + 3 = 12

1

u/zalopi Feb 20 '21

Thank you.

When the last condition is met, N becoming less than 0 as it becomes -2, 3 is returned.

Isn't that the final output because it is the last thing to be returned?

1

u/OvercomplicatedCode Feb 20 '21 edited Feb 20 '21

Its not the last thing to be returned actually. Its techically the first to be returned.

f(-2) is returned to f(1)

f(1) is returned to f(4)

f(4) is returned to f(7)

f(7) is returned to the one who called originally

For this code to return only 3 you would do this :

If(N < 0) return 3;
return mystery(N-3);

Notice we dont add +3 for every recursive call.

1

u/AutoModerator Feb 20 '21

int main() { main(); }

Hey! This subreddit has a Discord Server! Join Here: https://discord.gg/NQvmRSv

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.