+ 1
tail recursion - power function
I try to write power function using tail recursion but I still have StackOverflow problem what is wrong in the flowing code? // tail function long int TailRec (long int number , long int p_number , long int result = 1 ){ if (p_number == 1) return result ; else return TailRec (number , p_number-1 , number*result ); } //main function int main() { long int result = TailRec(2,2) ; cout<<result ; }
11 Respostas
+ 1
Your base case is wrong. The condition should be result==0 or !result (which is the same)
+ 1
With your code, on the code playground I had no error :/
+ 1
Yes, my bad, I did not read the code with enough attention and I did not know the French translation of tail recursion (even though I know how it works)
But when I run your code on the playground, even with 999 I do not get a Stack overflow
+ 1
You are welcome ^^
It can comes from the way you compile it :/
+ 1
Yes I know, I can't reproduce your bug so I can't help you, sorry :/
0
yeah I fix that one but still have StackOverflow problem
0
try something like
long int result = TailRec(2,999) ;
0
Firstly, 2^999 do not fit in long (max is 2^32-1 if signed, 2^64-1 if unsigned)
Secondly, you try to call a recursive function way to much (999 on sololearn playground is biiiig)
If you do not want this error, just derecursify the function (make it from recursive to iterative)
0
oh, man, you are accessible 24 H in a day! :)) thank a lot, after all these notes, I just can sum up that I don't know what is wrong with my machine!
0
I even wrote this code for python 3 and I got the same result
0
the real problem is, tail recursive duty is that to stopping overflow (make it from recursive to iterative) and in the Theory the tail function we have just call another function and go out of stack