tail recursion - power function

I try to write power function using tail recursion but I don't get the right answer what is wrong?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 // tail function
long int TailRec (int number , int p_number , int counter = 1 ){

    if (p_number == 1) return counter ;
    else  TaillRecr (number , p_number-1 , number*counter );
}

//main function
int main()
{
   
    long int result = TaiRec(2,2) ;
    cout<<result ; 
}
//out put 
2
Last edited on
It's just that you're stopping too early. When p_number is 1 you still have to multiply the counter one last time.
Thanks, I fixed that silly mistake but I have and another question is this really a tail recursive function?
Last edited on
it does not look complete. there is no return statement on the else?
I mean it probably works, but seems like all paths should return a value.

It does appear to be tail recursion.

Last edited on
yeah you right but with or without return after else I still have stack overflow problem
Also, you're return value is a long int but since the base case only ever returns an int, you'll lose the added precisions. To fix this, change parameter counter to be long int.

I also suggest that you rename counter to something like result. It doesn't count anything. It's actually the intermediate result.
You don't actually need the counter variable at all. Instead you could multiply the number with the return value directly.

 
return number * TailRec(number, p_number - 1);

Topic archived. No new replies allowed.