Advertisement
NikolaDimitroff

Fibonacci Sequence With LRR

Jul 11th, 2013
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.55 KB | None | 0 0
  1. using System;
  2. using System.Diagnostics;
  3.  
  4. class Program
  5.     {
  6.         static void Main(string[] args)
  7.         {
  8.         int maxFib = 92;
  9.         int testCount = 1000000;
  10.  
  11.         TimeSpan time = TestFibonacci(maxFib, testCount, FibonacciLRR);
  12.         Console.WriteLine("Direct formula: {0}", time);
  13.  
  14.         time = TestFibonacci(maxFib, testCount, FibonacciDP);
  15.         Console.WriteLine("Dynamic programming: {0}", time);
  16.         }
  17.  
  18.         private static TimeSpan TestFibonacci(int maxFib, int testCount, Func<int, long> fibonacciImplementation)
  19.         {
  20.             Stopwatch watch = new Stopwatch();
  21.             TimeSpan time = TimeSpan.Zero;
  22.             for (int fib = 2; fib < maxFib; fib++)
  23.             {
  24.                 watch.Reset();
  25.                 watch.Start();
  26.                 for (int i = 0; i < testCount; i++)
  27.                 {
  28.                     fibonacciImplementation(fib);
  29.                 }
  30.                 watch.Stop();
  31.                 time += watch.Elapsed;
  32.                 // Uncomment the next line to see the running time for each number
  33.                 // Console.WriteLine("{0} - was calculated a million times in: {1}", fib, watch.Elapsed);
  34.             }
  35.             return time;
  36.         }
  37.  
  38.         static long FibonacciDP(int n)
  39.         {
  40.             long[] table = new long[n + 1];
  41.             table[0] = 0;
  42.             table[1] = 1;
  43.  
  44.             for (int i = 2; i < n + 1; i++)
  45.             {
  46.                 table[i] = table[i - 1] + table[i - 2];
  47.             }
  48.  
  49.             return table[n];           
  50.         }
  51.  
  52.         static double GoldenRatio = (1 + Math.Sqrt(5)) / 2;
  53.         static double ReciprocalGoldenRatio = - 1 / GoldenRatio;
  54.         static double ReciprocalSqrtFive = 1 / Math.Sqrt(5);
  55.         static long FibonacciLRR(int n)
  56.         {
  57.             return (long)(ReciprocalSqrtFive * (Math.Pow(GoldenRatio, n) - Math.Pow(ReciprocalGoldenRatio, n)));
  58.         }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement