Today, we study the next Fibonacci algorithm, which realizes the value of nth in both recursive and non-recursive ways.
The code is as follows:
recursive mode: Public Static int getfib (int a) { if (a==1| | a==2) {return 1;} return getfib (a-2) +getfib (A-1); }
non-recursive mode: Public Static intGETFIB2 (inta) { intX=1; intY=1; if(a==1| | a==2){ return1; } for(inti=3;i<=a;i++){ inttemp=y; Y=x+y; X=temp; } returny; }
print out the top n items, 5 per line public static void listfib (int a) {StringBuilder sb = new StringBuilder (); for (int I=1;i<=a;i++ + "" if (i%5 = = 0 "\ n"
Test: Public Static void Main (string[] args) { listfib (+); }
Test results:
Comparing the recursive and non-recursive algorithms, it is found that the recursive algorithm is inefficient, the main reason is that recursion involves repeated computation, can be mitigated by caching, in particular, the calculation of each record into a map, the need for direct get without recalculation, optimized after the code as follows:
add cache-Optimized recursive algorithm: public static int getfib (int a) {map <integer, integer> Map = new< /span> Hashmap<integer, Integer> (); if (a==1| | a==2) {return 1;} if (Map.containskey (a)) { return Map.get (a); } Integer B = Getfib (a-2) +getfib (A-1 return b; }
Fibonacci Sequence algorithm