The tail recursive functions considered better than non tail recursive functions as tail-recursion can be optimized by compiler.
The above function can be written as a tail recursive function. The idea is to use one more argument and accumulate the factorial value in second argument. When n reaches 0, return the accumulated value.
Read full article from Tail Recursion | GeeksforGeeks
Can a non-tail recursive function be written as tail-recursive to optimize it?
Consider the following function to calculate factorial of n. It is a non-tail-recursive function. Although it looks like a tail recursive at first look. If we take a closer look, we can see that the value returned by fact(n-1) is used in fact(n), so the call to fact(n-1) is not the last thing done by fact(n).
Consider the following function to calculate factorial of n. It is a non-tail-recursive function. Although it looks like a tail recursive at first look. If we take a closer look, we can see that the value returned by fact(n-1) is used in fact(n), so the call to fact(n-1) is not the last thing done by fact(n).
unsigned int fact(unsigned int n) { if (n == 0) return 1; return n*fact(n-1); } |
unsigned factTR(unsigned
int
n, unsigned
int
a)
{
if
(n == 0)
return
a;
return
factTR(n-1, n*a);
}
// A wrapper over factTR
unsigned
int
fact(unsigned
int
n)
{
return
factTR(n, 1);
}