Here's how it's recursive:
Private Static int Fib_re (int N) { Re_count++ ; if (n<=1) { return1; } Else { return fib_re (n1) + fib_re (n-2);} }
Here is the dynamic plan:
Private Static int Fib_fast (int n,dictionary<intint> dic) { Fa_count++ ; if (! DiC. ContainsKey (n)) { dic. ADD (n, fib_fast (n-1, DIC) +fib_fast (n-2, dic); } return dic[n]; }
Test process:
Const intNUM = +; Stopwatch SW=NewStopwatch (); Sw. Start (); intResult_re =fib_re (NUM); Sw. Stop (); Console.WriteLine ("fib_re ({0}) ={1}: Time: {2}, Times: {3}", Num,result_re, SW. Elapsedticks, Re_count); Sw. Reset (); Sw. Start (); Dictionary<int,int> dic =Newdictionary<int,int>(); Dic. ADD (0,1); Dic. ADD (1,1); intRESULT_FA =Fib_fast (num,dic); Sw. Stop (); Console.WriteLine ("Fib_fast ({0}) ={1}: Time: {2}, Times: {3}", NUM,RESULT_FA, SW. Elapsedticks, Fa_count);
Results:
Time is nearly 20,000 times times ...
Dynamic programming comparing recursive----to Fibonacci sequence for example