Iterative and recursive detailed _java in Java

Source: Internet
Author: User
Tags mathematical functions

Objective

Recently in reading the time to see this content, the feeling is quite rewarding. Iterations use loops (for,while,do...wile) or iterators to exit when the loop condition is not satisfied. Recursion, in general, is a function of recursion, can be itself called itself, can also be a direct call, that is, method A calls method B, and Method B in turn calls method A, the condition of recursive exit is If,else statement, when the conditions are in line with the base exit.

The above are iterative and recursive syntax features, what are their differences in Java? Below is a detailed understanding of this article.

First, recursive

When it comes to iterations, you have to mention a mathematical expression:n!=n*(n-1)*(n-2)*...*1

There are many ways to compute factorial. People with a certain mathematical basis know n!=n*(n-1)! that the implementation of the code can therefore be written directly:

Code A

int factorial (int n) {
 if (n = = 1) {return
  1;
 } else {return
  n*factorial (n-1);
 }

In the execution of the above code, in fact, the machine is to perform a series of multiplication: → → → factorial(n) factorial(n-1) factorial(n-2) ... → factorial(1) . Therefore, continuous tracing (tracking the results of the last calculation) is required and multiplication is called to compute (build a multiplication chain). This type of operation that constantly calls itself is called recursion. Recursion can be further divided into linear recursive and recursive recursion. The amount of information that is linearly increasing with the input of the algorithm is called linear recursion. The computational n! (factorial) is linear recursion. Because as n increases, the time required for the calculation increases linearly. Another type of information that grows exponentially as input grows is called tree recursion.

Second, iterative

Another way to compute n! is to calculate 1 times 2, then multiply the result by 3, and then multiply the result by 4. Always multiply to n. In the implementation of the program, you can define a counter, each time multiplication, the counter is added once, until the value of the counter is equal to N. The code is as follows:

Code two

int factorial (int n) {
 int product = 1;
 for (int i=2; i<n; i++) {
  product *= i;
 }
 return product;
}

Code two does not build a multiplication chain compared to code one. In each step of the calculation, you only need to know the current result (product) and I of the value. This form of computation is called an iteration. There are several conditions for an iteration: 1, there is a variable with an initial value. 2, a rule that describes how variable values are updated. 3, an end condition. (Cyclic three elements: cyclic variable, loop body and cyclic termination condition). The same as recursion. Time requirements can be called linear iterations as the input grows linearly.

Iii. iterative VS. recursion

Comparing two programs, we can find that they look almost the same, especially in terms of their mathematical functions. When calculating n!, their calculated steps are proportional to the value of N. But if we stand at the point of the program and consider how they are running, then the two algorithms are very different.

(Note: In the original text about its difference write a bit, here is not translated, the following is the author's own summary content.) )

The first analysis of recursion, in fact, is that the most recursive one is to decompose a complex algorithm into some of the same repeatable steps. Therefore, using recursion to implement a computational logic often requires only a very short code to solve, and such code is relatively easy to understand. However, recursion means a lot of function calls. The local state of the function call is recorded with the stack. So, this can waste a lot of space, and if recursion is too deep, it can cause a stack overflow.

Next, analyze the iterations. In fact, recursion can be replaced with iterations. However, compared to the simple and easy to understand the recursion, iterations are more blunt and difficult to understand. Especially when it comes to a more complicated scene. However, the difficult to understand the code is a bit more obvious. Iterations are more efficient than recursion and are less expensive to use in space.

There must be iterations in recursion, but there is not necessarily recursion in the iterations, and most of them can be converted to each other.

Recursive call functions not only waste space, but can also easily overflow the stack if recursion is too deep.

Four, number-form recursion

As described earlier, tree recursion increases exponentially with the amount of information that is entered. The typical Fibonacci sequence is:

The sum of the first two digits in the Fibonacci sequence is equal to the third digit: 0,1,1,2,3,5,8,13,21 ...

The recursive implementation code is as follows:

int fib (int n) {
 if (n = = 0) {return
  0;
 } else if (n = = 1) {return
  1;
 } else {return
  fib (n-1) + fib (n-2);
 }

In the calculation process, in order to calculate fib(5) , the program must first calculate fib(4) and, want to fib(3) calculate fib(4) , the program also needs to calculate fib(3) and fib(2) . Two times fib (3) were computed in this process.

From the above analysis of the calculation process can draw a conclusion: the use of recursion to achieve the Fibonacci sequence has redundant computation.

As mentioned above, recursive algorithms can generally be implemented iteratively, as are the calculations of Fibonacci sequences.

int fib (int n) {
 int fib = 0;
 int a = 1;
 for (int i=0; i<n; i++) {
  int temp = FIB;
  FIB = fib + A;
  A = temp;
 }
 return fib;
}

Although there are redundant computations in the way of recursion, you can use iterations instead. But that does not mean that recursion can be completely superseded. Because recursion has better readability.

Summarize

The above is the entire content of this article, I hope the content of this article for everyone to learn or use Java can help, if you have questions you can message exchange.

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.