+ 1

tail recursion - power function

I try to write power function using tail recursion but I don't get the right answer what is wrong? // tail function long int TailRec (int number , int p_number , int counter = 1 ){ if (p_number == 1) return counter ; else TailRec (number , p_number-1 , number*counter ); } //main function int main() { long int result = TailRec(2,2) ; cout<<result ; } //out put 2

15th Jul 2017, 3:51 PM
Navid Tak
Navid Tak - avatar
3 Answers
+ 1
change your test to if (!p_number) return counter; And it will work fine
15th Jul 2017, 1:36 PM
Ali Rashidi
Ali Rashidi - avatar
+ 1
number! =1 for first run. so it goes to else and returns 2*1
15th Jul 2017, 1:39 PM
Gurpreet Singh
Gurpreet Singh - avatar
0
thank u guys, I fixed that silly mistake but i have and another question is this really a tail recursive function?
15th Jul 2017, 4:14 PM
Navid Tak
Navid Tak - avatar