Created
November 13, 2012 18:47
-
-
Save elicwhite/4067614 to your computer and use it in GitHub Desktop.
Fibonacci with Memoization
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Program | |
{ | |
static Dictionary<int, int> nums; | |
static void Main(string[] args) | |
{ | |
int testNum = 35; | |
int loops = 20; | |
nums = new Dictionary<int, int>(); | |
nums.Add(0, 0); | |
nums.Add(1, 1); | |
Stopwatch sw = Stopwatch.StartNew(); | |
for (int i = 0; i < loops; i++) | |
{ | |
fib(testNum); | |
} | |
sw.Stop(); | |
Console.WriteLine("Time used (fib): {0} ms", sw.Elapsed.TotalMilliseconds); | |
sw.Reset(); | |
sw.Start(); | |
for (int i = 0; i < loops; i++) | |
{ | |
fibMemo(testNum); | |
} | |
sw.Stop(); | |
Console.WriteLine("Time used (fibMemo): {0} ms", sw.Elapsed.TotalMilliseconds); | |
Console.ReadKey(); | |
} | |
public static int fibMemo(int n) | |
{ | |
if (nums.ContainsKey(n)) | |
{ | |
return nums[n]; | |
} | |
int result = fib(n - 1) + fib(n - 2); | |
nums.Add(n, result); | |
return result; | |
} | |
public static int fib(int n) | |
{ | |
if (n == 0 || n == 1) { | |
return n; | |
} | |
return fib(n - 1) + fib(n - 2); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment