Recursion and loop are two different typical solutions.
Recursive Algorithm:
Advantages: the code is concise, clear, and easy to verify. (If you really understand the algorithm, otherwise you will be dizzy)
Disadvantage: its operation requires a large number of function calls. If the number of call layers is relatively deep, additional stack processing is required, for example, parameter passing requires stack pressure and other operations, will have a certain impact on the execution efficiency. However, for some problems, if recursion is not used, it will be an extremely ugly code.
Loop algorithm:
Advantage: fast speed and simple structure.
Disadvantage: All problems cannot be solved. Some problems are suitable for Recursive instead of loop. If it is not difficult to use a loop, it is best to use a loop.
Summary of recursive and cyclic Algorithms
1. algorithms that can be processed by recursive calls also use loops to solve the need for additional inefficient processing.
2. After the current compiler is optimized, the efficiency of function processing for multiple calls will be very good, and the efficiency may not be lower than the loop.
The following are Java code implementations (recursive and recursive ):
[Java] import java. util. collections;
/**
* Fibonacci
*
* @ Author tongqian. Zhang
*/
Public class Fibonacci {
Public static void main (string [] ARGs ){
Required bytes = new bytes (system. In );
System. Out. println ("Please input this Fibonacci N :");
Int n = bytes. nextint (); // assume that the input is an integer greater than zero.
System. Out. println (FIG (6) + ":" + fig (6 ));
Int sum = 0;
For (INT I = 1; I <= N; I ++ ){
Sum + = maid (I );
}
System. Out. println (SUM );
}
// Recursive Implementation Method
Public static int maid (int n ){
If (n <= 2 ){
Return 1;
} Else {
Return maid (n-1) + maid (n-2 );
}
}
// Recursive Implementation Method
Public static int fibonaccinormal (int n ){
If (n <= 2 ){
Return 1;
}
Int n1 = 1, n2 = 1, Sn = 0;
For (INT I = 0; I <n-2; I ++ ){
Sn = N1 + N2;
N1 = n2;
N2 = Sn;
}
Return Sn;
}
}