The iterative is the person, the recursion is God. --l Peter Deutsch

Source: Internet
Author: User

Recursion, the mathematics inside called recursion, actually is the recursion relation. Middle School mathematics is a part of the recursive very typical practice, but teachers are not how to expand, new curriculum standard compulsory five second chapter series should be regarded as our first contact recursive concept.
In fact, when it comes to recursion, everyone knows that it is their own tune, so in fact we all understand, but how to adjust? How to control? And how do you see the result is what you want? Believe it or very faint, the following from the middle school math inside to see it.

The first part, two typical examples, arithmetic progression and geometric series

Actually this is actually an example, when teaching I often ask students: "What is arithmetic progression?" "Of course, the students will answer:" Is the last one more than the previous one number, this number does not change ... "also some said:" Is the last item minus a certain constant ... "
So we often use expressions to represent
A (n) =a (n-1) +d
Tex syntax for
\[a_n=a_{n-1}+d\]
That's a problem, OK? Of course not, I said the last one is 2 more than the previous one, what is this sequence?
It's 1,3,5,7,9, ... Or 2,4,6,8,10, ...
Of course it's not clear. Because the sequence we're talking about needs to have a first item, the value of the first item, so once we talk about the recursive sequence, there should be two things, one is the relationship between the successive items, the other is the first relationship.

Then you can use the overlay method to calculate:
Suppose the first item here is 1, which is a (1) = 1, and this constant is 2.
So
A (n) =a (n-1) +2
A (n-1) =a (n-2) +2
A (n-2) =a (n-3) +2
A (n-3) =a (n-4) +2
...
A (3) =a (2) +2
A (2) =a (1) +2
Add the left side of the equals sign, and the right is added in turn.
It is easy to find that a portion of the left side from a (2) has been added to a (n-1), the right part from a (2) has been added to a (n-1), then the left side of a (n), on the right left a (1) and N-1 2 added, the mathematical formula becomes
A (n) =a (1) +2 (n-1)
That
A (n) =1+2 (n-1)
The Latex code is
\[a_n=1+2 (n-1) \]

is arithmetic progression to the formula, then this recursive relationship can see a (n) =a (n-1) +x is the relationship between successive items, and a (1) =1 is the first item. Well, the relationship between this and the recursion is obvious.
A (n) =a (n-1) +x, which calls a (n) to execute a (n-1) +x, calls a (n-1) at the same time,... This continues, and finally when a (1) is not called function, directly return 1, and then all the way back, end recursion.

Take a look at the code to implement, or assume the first item is 1, the tolerance is 2

#include <stdio.h>

int main ()
{
int addfun (int);
int num;
printf ("Please input num:");
scanf ("%d", &num);
printf ("The result is%d", Addfun (num));
return 0;
}

int addfun (int n)
{
if (n = = 1)
{
return 1;
}
Return Addfun (n-1) + 2;
}
What about here? Addfun (n) is the previously seen a (n), in the process of the call to determine whether n is 1, if 1 of course it is now the first item, do not continue to call, directly return the result 1
The formula used here is not calculated in mathematics, purely by using recursive relationships to get results.

And look at geometric series. I believe it's clear, geometric series is the last item is the constant of the previous item, expressed as
A (n) =a (n-1) *q
The Latex code is
\[a_n=a_{n-1}\cdot Q\]
Change the function to be able to use, assuming the first item is 1, the male ratio is 2:
Intproductfun (int n)
{
if (n = = 1)

{
RETURN1;
}
Return Addfun (n-1) * *;
}

So leave a practice, this is a typical example of high school math (latex code):
The known sequence ~$\{a_n\}$~ satisfies ~ $a _n = 2a_{n-1}+1$, and the first item ~ $a _1 = 1$, and writes out the code procedure with a recursive call.
(Recursive relationship for a (n) =2a (n-1) +1,a (1) =1)

Reference code:
#include <stdio.h>
#include <stdlib.h>

int main ()
{
int Sumcon (int n);
printf ("%d", Sumcon (10));
return 0;
}

int Sumcon (int n)
{
if (n<=0)
{
return 1;
}
Return 2 * Sumcon (n-1) + 1;
}

Of course recursion does not have to call the function to complete, with a for loop can do
For example, the ratio is 2, the first item is 1 geometric series The value of the 10th item
can be written
#include <iostream>
UsingNamespace std;
Intmain ()
{
int res = 1;
for (int i=1; I <10; i++)
{
res = res * 2;
}
cout<<res<<endl;
return 0;
}
This can be roughly regarded as a recursive, res = res * 2 means the previous item is assigned twice times the next item, that is, the last item is equal to twice times the previous item, is not a recursive relationship ...


Second part, recursive call attention (direct recursion)

Recursive call in the programming is to a function, or method to self-off, then in the writing of recursive code has three points to note, first of all to pay attention to a problem, is the recursive relationship, here need to abstract a recursive relationship, not necessarily only two layers, perhaps three layers or more

For example: Stairs have n steps, go upstairs can step up to 1 order, also can step up 2 order, compile a program calculate total how many different way.

First of all, if there is only one step, then obviously there are only 1 kinds, so a (1) =1
If there are two steps, then there will be each on a layer, two times, and once on the two layer, that is, and 2 total 2 species, namely a (2) =2
When n=3, then there are 1+1+1, 1+2, 2+1 a total of 3 species, it seems to see no law, then analysis of the recurrence of relations, that is, the relationship between the items
Reached the third level there are two methods, one from the second floor to the third floor, then there is a (2) method, and can go from the first layer two steps to the third layer, namely a (1) method, beat the head, apparently reached the third layer has a (1) +a (2) method, then is not it? Verify
A (1) +a (2) =1+2=3, gee, right, looks a bit like, and then look at the fourth floor is not
When the n=4, according to the above analysis must be a (2) +a (3) =2+3=5, the following we enumerate: 1+1+1+1, 1+1+2, 1+2+1, 2+1+1, the two-way, just good, it seems that she!
Then there is the recursive relationship, that is, a (n) =a (n-1) +a (n-2), along with the value of the first entry: A (1) =1,a (2) = 2, because there are three items in the recursive relationship, it is clear that two initial values must be

Well, here's a note on recursion, and here's the second note, the critical condition
Since recursion is self-tuning, then how to stop it, obviously do not make logical judgments, the computer will continue to run, know that the program crashes (stack overflow), so you need to add an if judgment to jump out of recursion, in fact, is the first mentioned sequence, is here A (1) and a (2)
Then the code can be written like this:

int Count (int n)
{
if (2 = = N)
{
return 2;
}
else if (1 = = N)
{
return 1;
}
return count (n-1) + count (n-2);
}
In fact, this is a typical Fibonacci sequence, but the initial value is different, leaving the following two exercises (the famous series):
1, the inverse Fibonacci sequence, satisfies the recurrence relation is: A (n+2) =a (N)-A (n+1)
2, the BA-million series, to meet the recurrence relationship: A (n) =a (n-2) +a (n-3)

Now the third thing to pay attention to is the recursive body.
Let's look at two function codes (c + + code):
1.
voidtest_1 (int n)
{
cout<<n<<endl;
if (N < 6)
{
Test_1 (n + 1);
}
}
2.
voidtest_2 (int n)
{
if (N < 6)
{
Test_2 (n + 1);
}
cout<<n<<endl;
}
If you call these two functions separately in the main () function, what is the result of the execution?
Now let's assume that N is 0.
The first function prints out a
0
1
2
3
4
5
6
The second function prints out a
6
5
4
3
2
1
0
This is very strange, why is this?
In fact, the recursive relationship we consider earlier is a single recursive, but there are other execution codes in the two recursive bodies, in addition to the completion of recursion.
In fact, there are, but not shown, it is not detected
So how to analyze it?
In fact, it is very simple, recursive body can be divided into three parts, one is the head code, one is a recursive expression, one is the tail code, the difference between the end of the natural is recursive expression
Look at this code:
#include <iostream>
UsingNamespace std;
Intmain ()
{
void Test (int);
Test (1);
return 0;
}
Voidtest (int n)
{
cout<<n<<endl;
if (n < 3)
{
Test (n + 1);
cout<<n<<endl;
}
}
The output result is
1
2
3
2
1

So in this code, if () before the output stream is the header code, the middle of test (n + 1) is a recursive expression, where the tail code is still an output stream
So how do you analyze the program? Very simple, eight words
"Back and tail, waiting to return."
Head and tail apart, is to separate the two Cout<<n<<endl, the first Cout<<n<<endl execution, and then into the first recursion, waiting for the end of recursion to return to the second cout<<n< <endl Statement Execution
It's very abstract, and we'll analyze it one step at a moment.

First Call, N=1
The execution head Cout<<n<<endl, the output 1, and the tail Cout<<n<<endl waits, its value is also 1, but does not have the output;
Into the first recursion, n=2
Execution head Cout<<n<<endl, Output 2, and tail Cout<<n<<endl wait, its value is 2, but not output;
Into the second recursion, n=3
Execute head cout<<n<<endl, output 3, but Judge N < 3 is not established, that is no longer execute tail cout<<n<<endl statement, function body end
Back to the first recursive body, the execution waits for the tail Cout<<n<<endl, the output 2, the first recursive body ends, will take the outermost
Execution waits for the Cout<<n<<endl, Output 1, the entire function call ends, and returns to the main () function body to continue executing other commands.

The image is like an accordion, the function call begins to open the accordion, and then into the recursion, waiting for the inner end of the recursion to execute the following code
Eight words, "the tail is separated, waiting for the return."
In fact, this is the structure of the implemented stack

Here I basically end up with the recursive meaning I understand, and summarize:
Recursive invocation is recursive relationship
Recursive three note: Pay attention to recursive expression, pay attention to critical judgment, pay attention to recursive body

Excerpted from http://www.cnblogs.com/zzdxpq/

The iterative is the person, the recursion is God. --l Peter Deutsch

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.