using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; namespace Phabe { class Program { private static long[] Values; private static List<long> Values2; static void Main(string[] args) { Values = new long[200000]; Values[1] = 1; Values[2] = 1; Values2 = new List<long>(); Values2.Add(1); Values2.Add(1); for(int i=0;i<2000;i++) { Console.WriteLine("请输入项:"); int index = int.Parse(Console.ReadLine()); var bt = new Stopwatch(); bt.Start(); var ret = GetNumber(index); bt.Stop(); Console.WriteLine("第{0}种计算结果:{1},耗时{2}毫秒", 1,ret, bt.ElapsedMilliseconds); var bt2 = new Stopwatch(); bt2.Start(); var ret2 = GetNumber2(index); bt2.Stop(); Console.WriteLine("第{0}种计算结果:{1},耗时{2}毫秒", 2, ret2, bt2.ElapsedMilliseconds); var bt3 = new Stopwatch(); bt3.Start(); var ret3 = GetNumber3(index); bt3.Stop(); Console.WriteLine("第{0}种计算结果:{1},耗时{2}毫秒", 3, ret3, bt3.ElapsedMilliseconds); var bt4 = new Stopwatch(); bt4.Start(); var ret4 = GetNumber4(index-1); bt4.Stop(); Console.WriteLine("第{0}种计算结果:{1},耗时{2}毫秒", 4, ret4, bt4.ElapsedMilliseconds); var bt5 = new Stopwatch(); bt5.Start(); var ret5 = GetNumber5(index); bt5.Stop(); Console.WriteLine("第{0}种计算结果:{1},耗时{2}毫秒", 5, ret5, bt5.ElapsedMilliseconds); } } private static long GetNumber(int index) { long a = 1; long b = 1; long c = 1; for (int i = 2; i < index; i++) { c = a + b; a = b; b = c; } return c; } private static long GetNumber2(int index) { long a = 1; long b = 0; for (int i = 2; i < index; i++) { a += b; b = a - b; } return a + b; } private static long GetNumber3(int index) { long ret = Values[index]; if (ret == 0) { ret = GetNumber3(index - 1) + GetNumber3(index - 2); Values[index] = ret; } return ret; } private static long GetNumber4(int index) { while (Values2.Count <= index) { int count = Values2.Count; long temp = Values2[count - 1] + Values2[count - 2]; Values2.Add(temp); } return Values2[index]; } private static double GetNumber5(int n) { //直接利用其通项公式 (1/√5)*{[(1+√5)/2]^n - [(1-√5)/2]^n} return (1.0 / Math.Sqrt(5.0)) * (Math.Pow((1 + Math.Sqrt(5.0)) / 2.0, n) - Math.Pow((1 - Math.Sqrt(5.0)) / 2.0, n)); } } }
单纯比较1和2二种方案,哪个更优?为什么?
单纯比较3和4二种方案,哪个更优?为什么?
希望有人能帮我解释一下。