Reputation: 1
I was wondering if you would identify this as a head or tail recursive function:
int exponentiation(int x, int y){
if(!y) { return 1; }
return y > 1 ? x * exponentiation(x, y-1) : x;
}
Upvotes: 0
Views: 901
Reputation: 726987
This is not a tail recursion: returning the result of exponentiation
is not the last action taken by the function; the multiplication by x
is.
However, the function is easy to convert to a tail-recursive implementation by adding an extra parameter, exp:
int exponentiation_tail(int x, int y, int exp = 1){
if(y <= 0) { return exp; }
return exponentiation_tail(x, y-1, exp*x);
}
Upvotes: 3