View "recursion" from memory usage of Infinitus classification"

Source: Internet
Author: User
By simple application of recursion in the infinite classification, we can deeply analyze the inherent recursion. In PHP's infinite classification, many of the methods used are recursive, but our understanding of recursion is still vague. next we will have a deep understanding of the advantages and disadvantages of recursion, let everyone have a comprehensive understanding.

What is recursion?

Definition

Recursion (in mathematics and computer science) refers to the use of functions in the definition of functions.

The word Recursion is only "re-(again)" + "curs-(come, happen)", which means repeated occurrence and re-occurrence. The corresponding Chinese translation "recursion" expresses two meanings: "delivery" + "to". These two meanings are exactly the essence of recursive thinking. At this level, Chinese translation is more expressive.

I can see another analogy on the Internet:

Suppose you are in a cinema and want to know which row you are sitting in, but there are many people in front of you, so you are too lazy to count, then you asked the person in the previous row, "which row are you sitting in? 」, In this way, after the person (codenamed A) answers you, you will know which row you are in. just add one of the answers to A, that is, the row where you are located. Unexpectedly, A is lazy than you, and he doesn't want to count, so he also asked the person in front of him, "which row are you sitting in ?」, In this way, A can know its row in the same steps as you do. Then, B is doing the same thing. Until this string of people asked the first row, the first row told the person who asked the question "I am in the first row 」. Finally, everyone knows where they are.

Let's take the Fibonacci series as an example. In many textbooks or articles that involve recursion or computational complexity, the program for calculating the Fibonacci series is used as a classic example. If you want to use C # to write a function that calculates the Nth Number of the Fibonacci series at the fastest speed (ignore exceptions such as parameter less than 1 or result overflow ), I don't know if your program will be similar to the following code:

public static ulong Fib(ulong n){    return (n == 1 || n == 2) ? 1 : Fib(n - 1) + Fib(n - 2);}

This piece of code should be short and concise (only one line of code is executed), intuitive and clear, and very compliant with the Code Aesthetics of many programmers. it may be quite confusing for many people to write such code during interviews. However, if you use this code to calculate Fib (1000), I think it will never be better. its running time may drive you crazy.

It seems that good-looking code may not be used. if the program is unable to accept the efficiency, the beautiful things will be cloudification. If you analyze the execution stream of the program, you will find the problem. take the calculation of Fibonacci (5) as an example:

We can see that in the calculation of Fib (5), Fib (1) is calculated twice, Fib (2) is calculated three times, Fib (3) after two computation, nine computation is performed for only five computation tasks. This problem will become more and more prominent as the scale increases, so that Fib (1000) can no longer be calculated within an acceptable period of time.

We used a simple definition to calculate fib (n), that is, the formula fib (n) = fib (n-1) + fib (n-2 ). This idea is easy to think of, but a careful analysis we found that when calling fib (n-1), also call fib (n-2), that is, fib (n-2) two calls, the same principle, when calling f (n-2) f (n-3) also called twice, and these redundant calls are completely unnecessary. The complexity of this algorithm can be calculated exponentially.

Improved Fibonacci recursive algorithm

So is there a better recursive algorithm for calculating the Fibonacci series? Of course. Let's take a look at the first few items of the Fibonacci series:

11, 1, 2, 3, 5, 8, 13, 21, 34, 55...

Note No. if we remove the previous item, the resulting sequence still satisfies f (n) = f (n-1)-f (n-2), (n> 2 ), the sequence we get starts with 1 or 2. It is easy to find that the N-1 of this series is the nth of the original series. How do we know how to design algorithms? We can write a function that accepts three parameters. The first two are the first two of the series, the third is the number of columns starting with the previous two parameters.

1int fib_ I (int a, int B, int n );

In the function, we first check the value of n. If n is 3, we only need to return a + B, which is a simple situation. If n> 3, we call f (B, a + B, n-1 ), in this way, the problem scale is reduced (from the nth to the n-1 ). The final code is as follows:

int fib_i(int a, int b , int n){    if(n == 3)        return a+b;    else        return fib_i(b, a+b, n-1);}

Why is memory overhead high?

The principle of recursion is: first store the variable values to be calculated into the stack and cyclically, until the recursion end condition is met, the variable values to be calculated are retrieved from the stack, calculate the final result.
To calculate 10! =
Recursion: 10! = 10*9!
9! = 9*8!
......
2! = 2*1!
1! = 1
During calculation, it stores one expression in the memory until the recursion condition satisfies 1! = 1, and then extract the existing expression from the memory to get the final result. In this way, more system resources will be spent.

In addition, the system sets the maximum recursive depth. If the depth is greater than this value, an error is returned and the system exits. During recursive function calling, parameters and return values in the function are constantly pushed to the stack. Function calls will constantly use stacks, report to the site, and restore the site, so the memory overhead will increase. the solution is tail recursion. However, PHP has no optimization effect on tail recursion, therefore, this solution has no practical significance.

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.