斐波那契数列:1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233……
第一项和第二项是1,之后的每一项为之前两项的和。
递推:从初值出发反复进行某一运算得到所需结果。-----从已知到未知,从小到达(比如每年长高9cm,20年180,30后270)
递归:从所需结果出发不断回溯前一运算直到回到初值再递推得到所需结果----从未知到已知,从大到小,再从小到大(你想进bat,那么编程就的牛逼,就得卸载玩者农药,努力学习)。递归(Recursion)是从归纳法(Induction)衍生出来的。
class Program { static void Main(string[] args) { GetNumberAtPos(12); } static long GetNumberAtPos(int n) { return GetNumberAtPos(1, 1, 3, n); } /// <summary> /// /// </summary> /// <param name="fist"></param> /// <param name="second"></param> /// <param name="i">第几次了</param> /// <param name="n">第n项</param> /// <returns></returns> static long GetNumberAtPos(long fist, long second, int i, int n) { if(second==1) { Console.WriteLine(1); Console.WriteLine(1); } //currentCount是第n项的值 long currentCount = fist + second; Console.WriteLine(currentCount.ToString()); if (i < n) { long next = GetNumberAtPos(second, currentCount, ++i, n); } //else //{ // Console.WriteLine(currentCount.ToString()); //} return currentCount; } }
结果:
1
1
2
3
5
8
13
21
34
55
89
144
如果是想打印第n项的数据:
class Program { static void Main(string[] args) { //从第三项开始,运行到第100项 GetNumberAtPos(1, 1, 3, 100); } static long GetNumberAtPos(long first, long second, int i, int n) { long third = first + second; if (i < n) { long next = GetNumberAtPos(second, third, ++i, n); } else { Console.WriteLine(third.ToString()); } return third; } }
结果:3736710778780434371
递推法求大于100是第几项:
static void Main(string[] args) { long fn_1 = 1, fn_2 = 1, fn = 0; int i = 3; while (true) { fn = fn_1 + fn_2; if (fn > 100) { Console.WriteLine(i); break; } fn_1 = fn_2; fn_2 = fn; i++; } //从第三项开始,运行到第100项 //GetNumberAtPos(1, 1, 3, 100); }
结果:12