Skip to content

Instantly share code, notes, and snippets.

@TheSavior
Created November 13, 2012 18:47
Show Gist options
  • Save TheSavior/4067614 to your computer and use it in GitHub Desktop.
Save TheSavior/4067614 to your computer and use it in GitHub Desktop.
Fibonacci with Memoization
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