Is this tail-recursion? -
i wrote function calculate power of integer take modulus. wonder if did tail recursion :
int takemodulustailrecursion(int coef, int x, int n, int module){ int result = 0; if ( n > 0 ) result = takemodulustailrecursion( mod(coef * x, module), x , n - 1, module ); else if ( n == 0) result = mod ( coef , module ); return result; } //take modul of integer ( both negative , positive ) int mod(int x, int modul){ while ( x < 0) x += modul; return x % modul; }
here function using recursion purely, think different above :
int takemodulusnormrecursion(int x, int n, int module){ if ( n == 1 ) return mod( x, module ); else { int total = x * takemodulusnormrecursion( x, n - 1, module); return mod( total, module); } }
by way, can show me how check frame stack in eclipse in these cases ? tried ( not know right or wrong) , both take many stacks running.
whether tail recursion depends on how code compiled.
tail recursion happens when you're directly returning call function (possibly yourself). tail call optimization (the reason people care tail recursion) happens when compiler/interpreter notices this, , replaces current stack frame rather creating another. in case, if compiled naively, don't have tail recursion because you're making recursive call, assigning variable in call stack, later return. assignment step means you're doing additional stuff after calling other function, makes code stands not candidate tail call optimization.
however compiler should rewrite code so:
int takemodulustailrecursion(int coef, int x, int n, int module){ if ( n > 0 ) return takemodulustailrecursion( mod(coef * x, module), x , n - 1, module ); else if ( n == 0) return mod ( coef , module ); else return 0; } //take modul of integer ( both negative , positive ) int mod(int x, int modul){ while ( x < 0) x += modul; return x % modul; }
now tail recursive.
but whether tail call optimization happen depends on language , implementation. example if code supposed java, does jvm prevent tail call optimizations? points out, aren't going tail call optimization no matter do.
edit: saying "tail recursive" "tail recursive , tail call optimized".
Comments
Post a Comment