English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

I know it is something to do with the last operation but I am not sure. Thanks in advance for any help!!

2007-03-07 05:18:41 · 2 answers · asked by guy with many questions 2 in Computers & Internet Programming & Design

2 answers

tail recursion means that the last instruction in the method calls the method itself. In general, if it is tail-recursive it could usually be easily rewritten as a loop instead of using recursion at all.

To be truly tail recursive, there can be no other calls to the method itself except the very last line.

tail recursive:

int factorial( int n )
{
if (n <= 1) return 1;
return n*factorial(n-1);
}

recursive, but not tail recursive:

int splitmultiply( int a, int b )
{
if (a == 1) return b;
int prod = splitmultiply( a/2, b );
prod = prod+prod;
return prod;
}

2007-03-07 05:38:12 · answer #1 · answered by sspade30 5 · 0 0

FYI, tail recursive in Java is a good way to get a stack overflow error. Every time a method calls another method it is moved into memory while the other method is put onto the cpu. Java is synchronous, the method needs its return code before it will continue running. Even if it is the last line. So you you have a bunch of methods waiting for the methods they called to give a return code sitting in memory and they will eat up your stack fast.

So in short, you probably don't want to make a tail recursive method in Java expecially if you aren't controlling its input.

2007-03-08 06:27:33 · answer #2 · answered by saxondog 3 · 0 0

fedest.com, questions and answers