There is such a topic:
Recursive functions:
1 int x (int n)
2 {
3 if (n<=3)
4 {
5 return 1;
6 }
7 else
8 {
9 return x (n-2) +x (n-4) +1;
Ten }
11}
Calculates the number of recursive invocations of X (x (8)).
Most probably think it's a very simple topic, and it's really simple. But it takes a bit of patience to figure out the recursive call count correctly without a compiler.
X (x (8)) We first calculate X (8), we count the number of recursive calls with count=0
1.x (8) =x (6) +x (4) +1 count=1;
2.x (6) =x (4) +x (2) +1,x (4) =x (2) +x (0) +1 x (8) =x (4) +2*x (2) +x (0) +3 count=3;
3.x (4) =x (2) +x (0) +1 x (8) =3*x (2) +2*x (0) +4 count=4
4.x (2) =1,x (0) = 1; X (8) =9 count=9
Recalculate X (9)
1.x (9) =x (7) +x (5) +1 count=10
2.x (7) =x (5) +x (3) +1,x (5) =x (3) +x (1) +1 x (9) =x (5) +2*x (3) +x (1) +3 count=12
3.x (5) =x (3) +x (1) +1 x (9) =3*x (3) +2*x (1) +4 count=13
4.x (3) =1 x (1) =1 x (9) =3+2+4=9 count=18
Next we'll use the program to verify:
1 #include <iostream>
2 using namespace std;
3
4 static int count=0;
5
6 int x (int n)
7 {
8 if (n<=3)
9 {
ten count++; return 1;
All
Else ( count++); return x (n-2) +x (n-4) +1;
+ },
int main (void),
{ cout<< "x (x8) =" <<x (x (8)) < <endl; cout<< "count=" <<count<<endl; System ("pause"); return 0;
26}
To run a screenshot:
The validation is correct.
For this calculation recursive calls must be clear-minded, it is best to recursive all recursive calls to the place of recursive exit and then unified recursive exit calls, so it is not easy to cause confusion, personal opinion, for reference only.