The tail recursion calculates the result of this method and passes it directly to the next method. Very efficient.
General recursion, when the result of this method does not come out, call the next recursive, and the program will be part of the results in memory, until the end of the method, and then return to calculate. If the recursion is relatively large, it may be a memory overflow.
The practice proves that the tail recursion is higher than the normal recursion efficiency.
The following example, with the normal recursion needs 10s to complete, and with the tail recursion, only used 1s less than
Package com.zf.dg;/** * Title * There is a cow, the third year after birth, began to produce a cow every year (seemingly single-sex births, there is no bull what); the birth of the heifer also conforms to the same law, the third year after birth, the beginning of birth, each year to give birth to a cow; This kind of cow is immortal, and always has the fertility, the life not only, the birth not only, endless. In the first year, there was only one cow. How many cows are there in the first nth year? The law is as follows: number of nth years = number of cattle in year n-1 + number of cattle in n-2 Year 1 8 */public class Test2 {/** * normal tree recursion * @param n * @return */public static int fun (int n) {if (n < 3) {return 1;} Else{return Fun (n-1) + fun (n-2);}} /** * Turn normal tree recursion into tail recursion * from the current year until the beginning of the first year * The number of cattle in the last years of @param * @param the number of cows in the present year of results * @param current years * @param N Number of years to be calculated * @return */public static int fun2 (int last, int result, int. Current, int n) {if (n < 3) {return 1;} else if (current = = n) return result; Else{return fun2 (result, result + last, ++current, n);}} /** * Wrap the method above * ideas: From the second year onwards, counting to the nth year, because the next year we can know the number of cows in his previous year and the number of current years * @param n * @return */public static int Fun3 (i NT N) {return fun2 (1, 1, 2, n);} public static void Main (string[] args) {Long start = System.currenttimemillis (); System.out.println (fun);//system.out.println(FUN3); Long end = System.currenttimemillis (); System.out.println ("spents:" + (End-start)/1000);}}
Fibonacci (Fibonacci) series