C++ judge odd and even examples are introduced

  • 2020-04-01 21:30:43
  • OfStack

So far, the recursive functions you've seen are calling themselves directly. While most recursive functions fit this pattern, recursion is more broadly defined, and if a function is subdivided into several subfunctions, recursive calls can be applied at a deeper nesting level. For example, if function f calls function g, and function g in turn calls function f, the calls to these functions are still considered recursive. This type of Recursion is called interactive recursion
The following shows the application of interactive recursion by determining whether a number is even or odd, and this problem highlights the importance of recursive leap trust. First, let's look at the description of odd and even Numbers:
If the previous number is odd, the number is even
A tree is either even or odd
Let's say that 0 is even
Recursive jump trust
As you can see from the code, the implementation of the code is based entirely on the three points described above in the odd and even Numbers. At first sight, this is incredible. If you want to explore how the underlying implementation works, you can just plug in a smaller number and trace the call to verify. OK
On the face of it, the simple case of "define 0 to be even" really doesn't show that this recursion works. So, for situations that we can't see right away, what we need is trust in recursive jumps, and as long as we get the recursive decomposition right and the simple scenario analysis right, we don't have to worry about the implementation details and hand them over to the computer. Therefore, once you master recursive thinking, how simple and fast it is to solve a problem, how shocking it is
 
#include <iostream> 
using namespace std; 
bool isodd(unsigned); 
bool isodd(unsigned n) 
{ 
return !(iseven(n)); 
} 
bool iseven(unsigned n) 
{ 
if (n == 0) 
{ 
return true; 
} 
else 
{ 
return isodd(n-1); 
} 
} 
int main() 
{ 
cout << isodd(11) << endl; 
return 0; 
}  

Related articles: