Types of recursion
Linear recursive function
- makes a single call to itself each time the function runs. For example, a factorial function is linear recursion.
// an example of a recursive declaration of method factorial numbers
public long factorial( long n, int i )
{
// base case
if ( n == 1 )
return n;
// recursive step
else
{
i--;
return factorial( n*i, i );
}
}
Tail recursive
- a form of linear recursion where the recursive call is the last thing the function does, and in many cases the value of the recursive call is returned.
//a example of a recursive declaration of a method to compute greatest common denominators
int gcd(int m, int n)
{
int r;
if (m < n) return gcd(n,m); //one possible recursive call
r = m%n;
if (r == 0) return(n); //base case
else return(gcd(n,r)); //other recursive call
}
Binary Recursive
- recursive functions with two recursive calls.