Tagged with: Fibonacci memo recursive one Fibonacci demo RIP cache start
Why say " algorithm is the soul of the program is not too much", please see the following simple case
1 Packagerecursion;2 3 ImportJava.util.HashMap;4 ImportJava.util.Map;5 6 Importorg.junit.Test;7 8 /** 9 * @author: MengxianmanTen * @creationTime: November 27, 2017 morning 9:47:51 One * @description: The simple use of the Fibonacci sequence combination memo algorithm A */ - Public classMemorandumdemo { - //calculation method Execution times the Private Longcount; - //The map collection is used as a memo to hold the calculated value of Fibo (n) - PrivateMap<integer, long> map =NewHashmap<>(); - + //method One: Do not use the Map collection as the memo cache data - Public LongFibo (Integer N) { +count++; A if(n = = 1 | | n = = 2){ at return1; -}Else{ - returnFibo (n-1) + Fibo (n-2); - } - } - //method Two: Use the Map collection as a memo to cache data in Public LongFibo2 (Integer N) { -count++; to if(n = = 1 | | n = = 2){ + return1; -}Else{ the if(!Map.containskey (n)) { *Map.put (n, Fibo2 (n-1) + Fibo2 (n-2)); $ }Panax Notoginseng returnmap.get (n); - } the } + A @Test the Public voidtest1 () { + LongStart =System.currenttimemillis (); - Longresult = Fibo (50); $ LongEnd =System.currenttimemillis (); $SYSTEM.OUT.PRINTLN ("Calculated result:" +result); -SYSTEM.OUT.PRINTLN ("Time Consuming:" + (End-start) + "millisecond"); -System.out.println ("Method execution Count:" +count); the /*Test Results - * Calculation result: 12586269025Wuyi * Time consuming: 77318 Ms the * Method Execution times: 25172538049 - */ Wu } - About @Test $ Public voidtest2 () { - LongStart =System.currenttimemillis (); - Longresult = Fibo2 (50); - LongEnd =System.currenttimemillis (); ASYSTEM.OUT.PRINTLN ("Calculated result:" +result); +SYSTEM.OUT.PRINTLN ("Time Consuming:" + (End-start) + "millisecond"); theSystem.out.println ("Method execution Count:" +count); - /*Test Results $ * Calculation result: 12586269025 the * Time consuming: 0 Ms the * Method Execution times: the */ the } -}
Whether the Java programmer should know a bit about the algorithm (a simple recursive calculation of the Fibonacci sequence of the case illustrates the importance of the algorithm to the program)