tail recursion - power function

Jul 15, 2017 at 1:18pm
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 Jul 17, 2017 at 7:28am
Jul 15, 2017 at 1:35pm
It's just that you're stopping too early. When p_number is 1 you still have to multiply the counter one last time.
Jul 15, 2017 at 4:12pm
Thanks, I fixed that silly mistake but I have and another question is this really a tail recursive function?
Last edited on Jul 15, 2017 at 4:16pm
Jul 16, 2017 at 1:09am
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 Jul 16, 2017 at 1:11am
Jul 16, 2017 at 2:40pm
yeah you right but with or without return after else I still have stack overflow problem
Jul 16, 2017 at 2:49pm
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.
Jul 16, 2017 at 3:50pm
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.