-
Notifications
You must be signed in to change notification settings - Fork 0
/
FibonacciLookup.cs
66 lines (55 loc) · 1.66 KB
/
FibonacciLookup.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
using System;
using System.Diagnostics;
public class FibonacciLookup
{
private const int InitSize=20;
private static long[] _table;
public static void Main(string[] args)
{
_table=new long[InitSize];
int testNum = 42;
Console.WriteLine("Optimized Fibonacci function's result: {0} (faster)",Fibonacci(testNum));
Console.WriteLine("Old Fibonacci function's result: {0} (slower)",StandardFibonacci(testNum));
}
private static long Fibonacci(int a)
{
if (a < 2)
{
_table[a] = a;
return a;
}
if (a>=_table.Length)
{
while (a > _table.Length - 1)
{
long[] newTable=new long[_table.Length*2];
_table.CopyTo(newTable,0);
_table = newTable;
}
}
if (_table[a] != 0)
{
return _table[a];
}
long value = 0;
try
{
value = checked(Fibonacci(a - 1) + Fibonacci(a - 2));
}
catch
{
Console.WriteLine("The number is too big!");
return 0;
}
_table[a] = value;
return value;
}
private static long StandardFibonacci(int a)
{
if (a < 2)
{
return a;
}
return StandardFibonacci(a - 1) + StandardFibonacci(a - 2);
}
}