[转]C#算法 Fibonacci费波纳数列
1. 1,1,2,3,5,8,13,21,34....求其第30位是多少?
/// <summary> /// 1,1,2,3,5,8,13,21,34....求其第30位是多少? /// 递归算法 /// </summary> /// <param name="i"></param> /// <returns></returns> public static int Fibo(int i) { if (i == 0) return 1; else if (i == 1) return 1; else return Fibo(i - 1) + Fibo(i - 2); }
//递归算法 Console.WriteLine(Fibo(6)); //不用递归 int[] num = new int[30]; num[0] = 1; num[1] = 1; int first = num[0]; int second = num[1]; for (int i = 2; i < num.Length; i++) { num[i] = first + second; first = second; second = num[i]; } Console.WriteLine(num[6]);
2.
/// <summary> /// 1+2+3+4+5+...+100 /// </summary> /// <param name="i"></param> /// <returns></returns> public static int Fibo2(int i) { if (i == 1) return 1; else return Fibo2(i - 1) + i; } /// <summary> /// 1-2+3-4+5-6+7-8+9 /// </summary> /// <param name="i"></param> /// <returns></returns> public static int Fibo3(int i) { if (i == 1) return 1; if (i == 2) return 2; else return Fibo3(i - 2) + i; }
Console.WriteLine(Fibo2(100)); Console.WriteLine(Fibo3(9) - Fibo3(8));