Tail recursion = recursion + iteration ?, Tail recursion

Source: Internet
Author: User

Tail recursion = recursion + iteration ?, Tail recursion
0 Introduction

It usually involves recursion and iteration. recursion is intuitive, but it occupies too much memory and time. iteration is fast, but it is not as concise and clear as recursive code. Can we combine the advantages of these two algorithms? The answer is yes. tail recursion provides such a mechanism.

What is tail recursion?

To put it simply, tail recursion is wearing the coat of "recursion", but has an "iteration" heart. It looks like recursion, but iteration is performed internally. The following is an example.

2. factorial example 2.1 first look at the factorial Iteration Algorithm:

2.2 let's look at the recursive algorithm of factorial:

2.3 Finally, let's look at the tail recursion algorithm of the factorial:

3 Fibonacci series example 3.1 Let's first look at the iterative algorithm of the Fibonacci series:

3.2 let's look at the recursive algorithm of the Fibonacci series:

3.3 Finally, let's look at the ending recursive algorithm of the Fibonacci series:

Summary

As shown in the example, tail recursion always carries an "Iteration variable" to the depth of recursion, which is equivalent to side recursion and edge computing. When recursion is completed, the results are also calculated. It is worth mentioning that tail recursion only uses the shell of recursion, and its essence is still iterative. Therefore, efficiency should be similar to iteration.

 

Related Article

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.