public static int Fibonacci(int x) { var preValue = -1; var curValue = 1; for (int i = 0; i <= x; ++i) { var sum = preValue + curValue; preValue = curValue; curValue = sum; } return curValue; }
上面的代码当x的值为47的时候就会出现溢出,结果如下图:
现在修改代码,使用BigInteger,代码如下:
1 2 3 4 5 6 7 8 9 10 11 12
public static BigInteger Fibonacci(int x) { var preValue = new BigInteger(-1); var curValue = new BigInteger(1); for (int i = 0; i <= x; ++i) { var sum = preValue + curValue; preValue = curValue; curValue = sum; } return curValue; }
public static void SortedSetDemo() { int count = 0; var set1 = new SortedSet<int>() { 1,5,3,9,4,6}; foreach (int i in set1) { count++; Console.Write(i); if (count != set1.Count) Console.Write(","); } }
除了自排序外,还可以求出集合的最大值、最小值和制定范围的集合,看下面例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
public static void SortedSetDemo() { var set1 = new SortedSet<int>() { 8, 5, 3, 9, 4, 6 }; Console.WriteLine("MixValue:" + set1.Min); Console.WriteLine("MaxValue:" + set1.Max); Console.Write("SubSet:"); var subSet = set1.GetViewBetween(5, 9); int count = 0; foreach (int i in subSet) { count++; Console.Write(i); if (count != subSet.Count) Console.Write(","); } }