theory - Tail v. Head Recursion -
i wondering if identify head or tail recursive function:
int exponentiation(int x, int y){ if(!y) { return 1; } return y > 1 ? x * exponentiation(x, y-1) : x; }
this not tail recursion: returning result of exponentiation
not last action taken function; multiplication x
is.
however, function easy convert tail-recursive implementation adding 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); }
Comments
Post a Comment