We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Your solution is recursive but it's not a tail recursion (it's important when using C/C++ with GCC that optimizes tail calls).
So it will stack the function calls because of the
(received/2)+...
On top of that you're computing "(received / 2)" twice per call.
It would be better to iterate instead of using non tail recursive call, like the following :
intcountLikesOnDay(intday){intreceived=5;intcumulative=0;for(inti=0;i<day;i++){received/=2;cumulative+=received;received*=3;}returncumulative;}// ...// somewhere in main()countLikesOnDay(day);
Or transform it to a tail recursive call like the following :
intcountLikesOnDayAux(intday,intreceived,intcumulative){if(day==0)returncumulative;elsereturncountLikesOnDayAux(day-1,(received/2)*3,cumulative+(received/2));}intcountLikesOnDay(intday){returncountLikesOnDayAux(day,5,0);}// ...// somewhere in main()countLikesOnDay(day);
(I don't know how to avoid computing "(received / 2)" twice in the tail recursive call).
using a lot of space (to remember each previous call) and time (to compute the whole stack at the end of the recursion), while iteration and tail recursion (when optimized) are using just the number of parameters in space, and small calculations per call, not a big one at the end.
But for sure, non tail recusive calls, will always be the easiest way of reading an algorithm, that's why your solution is the most readable solution, but not the most elegant, I don't agree with that.
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Viral Advertising
You are viewing a single comment's thread. Return to all comments →
Your solution is recursive but it's not a tail recursion (it's important when using C/C++ with GCC that optimizes tail calls). So it will stack the function calls because of the
On top of that you're computing "(received / 2)" twice per call. It would be better to iterate instead of using non tail recursive call, like the following :
Or transform it to a tail recursive call like the following :
(I don't know how to avoid computing "(received / 2)" twice in the tail recursive call).
That's just an advice, just remember that
using a lot of space (to remember each previous call) and time (to compute the whole stack at the end of the recursion), while iteration and tail recursion (when optimized) are using just the number of parameters in space, and small calculations per call, not a big one at the end.
But for sure, non tail recusive calls, will always be the easiest way of reading an algorithm, that's why your solution is the most readable solution, but not the most elegant, I don't agree with that.