Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Diagnostics;
- class Program
- {
- static void Main(string[] args)
- {
- int maxFib = 92;
- int testCount = 1000000;
- TimeSpan time = TestFibonacci(maxFib, testCount, FibonacciLRR);
- Console.WriteLine("Direct formula: {0}", time);
- time = TestFibonacci(maxFib, testCount, FibonacciDP);
- Console.WriteLine("Dynamic programming: {0}", time);
- }
- private static TimeSpan TestFibonacci(int maxFib, int testCount, Func<int, long> fibonacciImplementation)
- {
- Stopwatch watch = new Stopwatch();
- TimeSpan time = TimeSpan.Zero;
- for (int fib = 2; fib < maxFib; fib++)
- {
- watch.Reset();
- watch.Start();
- for (int i = 0; i < testCount; i++)
- {
- fibonacciImplementation(fib);
- }
- watch.Stop();
- time += watch.Elapsed;
- // Uncomment the next line to see the running time for each number
- // Console.WriteLine("{0} - was calculated a million times in: {1}", fib, watch.Elapsed);
- }
- return time;
- }
- static long FibonacciDP(int n)
- {
- long[] table = new long[n + 1];
- table[0] = 0;
- table[1] = 1;
- for (int i = 2; i < n + 1; i++)
- {
- table[i] = table[i - 1] + table[i - 2];
- }
- return table[n];
- }
- static double GoldenRatio = (1 + Math.Sqrt(5)) / 2;
- static double ReciprocalGoldenRatio = - 1 / GoldenRatio;
- static double ReciprocalSqrtFive = 1 / Math.Sqrt(5);
- static long FibonacciLRR(int n)
- {
- return (long)(ReciprocalSqrtFive * (Math.Pow(GoldenRatio, n) - Math.Pow(ReciprocalGoldenRatio, n)));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement