Tail recursion and Java

Source: Internet
Author: User

Simply put, recursion is called itself. All recursion should have at least one basic condition, without recursion when basic conditions are met.

Give a recursive example:

1 int fact (int  N) {2     if(n==1)3         return 1; 4     Else 5         return N*fact (N-1); 6 }        

The execution of each recursive method is divided into two stages of forward and fallback, the above example calculates the factorial of 5, the result of the forward stage is:

(5* ((1)))

The fallback phase calculates the values in parentheses, in turn, by inward.

Applied to the program, respectively, corresponding to the stack and the stack. With this approach in mind, each call will be stacked out of the stack, which is inefficient. In addition, each recursive creation of a new stack when the recursion depth is too deep, it will cause a stack overflow, that is, can be divided into the creation of the stack of low memory situation. The method of tail recursion is presented.

Tail recursion, simply put, is to write the recursive statement to the last line and not participate in any calculations. Overwrite the previous example with the tail recursion as:

1 intFactintN) {2     if(n==1)3         return1;4     Else5         returnFact (n-1,n);6 }       7 8 intFactintNintM) {9     if(n==1)Ten         returnM; One     Else A         returnFact (N-1, nM); -}

But this requires the compiler to optimize for tail recursion, each time it is reused or overwrites the stack of the original recursive method, rather than the new stack. Unfortunately, both Java and Python do not support tail-recursive optimizations, and Java's tail-recursive code is no different from normal recursion. Perhaps the JVM is trying to better output stack information in the event of an exception. Therefore, in Java, it is generally possible to use iterations instead of recursion.

Tail recursion and Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.