If we need to calculate the same problem multiple times, we can usually choose recursion or loop.
The advantage of recursion is that the Code is concise.
But recursion also has obvious disadvantages:
- Recursion is caused by function calls, which consume time and space. Each function call needs to allocate space in the memory stack to save parameters, return addresses and temporary variables, and it takes time to load data and pop-up data into the stack.
- Recursion may involve repeated computations. The essence of recursion is to break down a big problem into small problems, but there will be overlapping parts between multiple small problems.
- Recursion may cause problems: Call Stack Overflow.
Fibonacci Series
Public class exam9_fibonacci {public static void main (string [] ARGs) {int n = 10; // recursion long start = system. currenttimemillis (); system. out. println ("WHEN n =" + N + ", the result is" + maid (n); long end = system. currenttimemillis (); system. out. println ("recursion:"); system. out. println ("the running time is" + (end-Start) + "Ms"); // loop long start1 = system. currenttimemillis (); system. out. println ("\ n loop mode:"); circulation (n); long end1 = system. currenttimemillis (); system. out. println ("RunTime is" + (end1-start1) + "Ms");} // use recursive Private Static long Fibonacci (int n) {If (n <= 0) return 0; If (n = 1) return 1; return fig (n-1) + fig (n-2);} // use the loop method Private Static long circulation (int n) {If (n <= 0) return 0; If (n = 1) return 1; long finsone = 0; long finstwo = 1; long fiber n = 0; for (INT I = 2; I <= N; I ++) {fiber = finsone + finstwo; finsone = finstwo; finstwo = fiber N;} return fiber ;}}
The result is:
N Value |
Final Result |
Recursive Method for Fibonacci ()
Number of times a method is called |
Recursive Method time (MS) |
Circulation Method (MS) |
10 |
55 |
177 |
1 |
0 |
20 |
6765 |
21891 |
3 |
0 |
30 |
832040 |
2692537 |
14 |
0 |
40 |
102334155 |
331160281 |
1254 |
0 |
50 |
12586269025 |
40730022147 |
150514 |
0 |
60 |
|
|
Too long |
|
Obviously, the time is complex:
The recursion method increases exponentially by N.
The loop is O (n)
Therefore, for the Fibonacci series, the loop method is better.