斐波拉契数列:
1,1,2,3,5,8,13,21,34,55,89......
n=1或n=2时,1
n>2 时,An=A(n-1)+A(n-2);
两种实现方法:
递归:这是面试官更想要的结果,尽管实现方式很多
1 #region 递归实现 2 /// <summary> 3 /// recursive 递归 4 /// </summary> 5 public static int Recursive(int position) 6 { 7 if (position == 1 || position == 2) 8 return 1; 9 else 10 return Recursive(position - 1) + Recursive(position - 2); 11 } 12 #endregion
While循环:使用python语音写这个方法,代码会少很多(使用 a,b = b,a+b 一句代码代替了 数据换位操作)
1 #region 循环实现 2 /// <summary> 3 /// While循环 4 /// </summary> 5 /// <param name="position"></param> 6 /// <returns></returns> 7 public static int WhileMath(int position) 8 { 9 int curr=1; //n 10 int firstNum = 0;//a 11 int SeondNum = 1;//b 12 13 int tmp = 0; 14 while (curr < position) 15 { 16 Console.Write(string.Format("{0,5},",SeondNum)); 17 18 tmp = firstNum; 19 firstNum=SeondNum; 20 SeondNum+=tmp; 21 22 curr++; 23 } 24 Console.Write(string.Format("{0,5},", SeondNum)); 25 26 Console.Write(" "); 27 return SeondNum; 28 } 29 #endregion
示例代码:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 /* 7 * 1,1,2,3,5,8,13,21,34,55,89...... 8 * 9 * n>2:An=A(n-1) + A(n-2) 10 * */ 11 namespace 斐波拉契数列 12 { 13 14 class Program 15 { 16 static void Main(string[] args) 17 { 18 Console.WriteLine("斐波拉契数列: 1,1,2,3,5,8,13,21,34,55,89,144......"); 19 //使用递归实现: 20 Console.WriteLine("递归实现:"); 21 Console.WriteLine(string.Format("n=5,value={0}", Recursive(5))); 22 Console.WriteLine(string.Format("n=10,value={0}", Recursive(10))); 23 Console.WriteLine(); 24 //使用循环实现 25 Console.WriteLine("while循环实现:"); 26 Console.WriteLine(string.Format("n=5,value={0}", WhileMath(5))); 27 Console.WriteLine(string.Format("n=10,value={0}", WhileMath(10))); 28 Console.WriteLine(); 29 30 Console.Read(); 31 32 } 33 34 #region 递归实现 35 /// <summary> 36 /// recursive 递归 37 /// </summary> 38 public static int Recursive(int position) 39 { 40 if (position == 1 || position == 2) 41 return 1; 42 else 43 return Recursive(position - 1) + Recursive(position - 2); 44 } 45 #endregion 46 47 #region 循环实现 48 /// <summary> 49 /// While循环 50 /// </summary> 51 /// <param name="position"></param> 52 /// <returns></returns> 53 public static int WhileMath(int position) 54 { 55 int curr=1; //n 56 int firstNum = 0;//a 57 int SeondNum = 1;//b 58 59 int tmp = 0; 60 while (curr < position) 61 { 62 Console.Write(string.Format("{0,5},",SeondNum)); 63 64 tmp = firstNum; 65 firstNum=SeondNum; 66 SeondNum+=tmp; 67 68 curr++; 69 } 70 Console.Write(string.Format("{0,5},", SeondNum)); 71 72 Console.Write(" "); 73 return SeondNum; 74 } 75 #endregion 76 77 } 78 }
运行效果: