+ 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 ; }

17th Jul 2017, 7:41 AM
Navid Tak
Navid Tak - avatar
11 Réponses
+ 1
Your base case is wrong. The condition should be result==0 or !result (which is the same)
17th Jul 2017, 8:13 AM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
+ 1
With your code, on the code playground I had no error :/
17th Jul 2017, 10:51 AM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
+ 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
17th Jul 2017, 9:58 PM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
+ 1
You are welcome ^^ It can comes from the way you compile it :/
18th Jul 2017, 4:33 AM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
+ 1
Yes I know, I can't reproduce your bug so I can't help you, sorry :/
18th Jul 2017, 10:43 AM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
0
yeah I fix that one but still have StackOverflow problem
17th Jul 2017, 10:17 AM
Navid Tak
Navid Tak - avatar
0
try something like long int result = TailRec(2,999) ;
17th Jul 2017, 1:01 PM
Navid Tak
Navid Tak - avatar
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)
17th Jul 2017, 2:03 PM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
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!
17th Jul 2017, 10:17 PM
Navid Tak
Navid Tak - avatar
0
I even wrote this code for python 3 and I got the same result
18th Jul 2017, 5:51 AM
Navid Tak
Navid Tak - avatar
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
18th Jul 2017, 5:55 AM
Navid Tak
Navid Tak - avatar