# On the calculation of recursion number

Source: Internet
Author: User

There is such a topic:

Recursive functions:

`1 intXintN)2 {3     if(n<=3)4     {5         return 1;6     }7     Else8     {9         returnX (n2) +x (n4)+1;Ten     } One}`

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 to correctly calculate this recursion without a compiler

The number of calls actually requires a bit of patience.

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 namespacestd;3 4 Static intCount=0;5 6 intXintN)7 {8     if(n<=3)9     {Tencount++; One         return 1; A     } -     Else -     { thecount++; -         returnX (n2) +x (n4)+1; -     } - } +  - intMainvoid) + {  Acout<<"x (x8) ="<<x (X (8)) <<Endl; atcout<<"count="<<count<<Endl; -System"Pause"); -     return 0; -}`

Run:

The validation is correct.

For this calculation recursive calls must be clear-minded, it is best to recursive all recursive calls to the recursive exit

Local re-unification of the call for the export of the recursive, so not prone to confusion, personal opinion, for reference only.

On the calculation of recursion number

Related Keywords:

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.