斐波那契數列: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