AI智能
改变未来

c# 常用递归算法(斐波那契数列,阶乘,猴子选大王)等

一 斐波那契数列:

public static int f(int x){Console.WriteLine(x);if (x <=2)return 1;elsereturn f(x-2) + f(x - 1);}

二 阶乘:

public static int f(int x){if (x == 1)return 1;elsereturn x * f(x - 1);}

三 猴子选大王:

public static int f(int x, int n){int[] p = new int[x];int i, j, t;for (i = 0; i < x; i++)p[i] = i + 1;t = 0;for (i = x; i >= 1; i--){t = (t + n - 1) % i;for (j = t + 1; j <= i - 1; j++)p[j - 1] = p[j];}return p[0];}

四 m^n:

public static int f(int i, int j){if(j == 0)return 1;if(k == 1)return i;return i * f(i, j - 1);}

五 1+2+…+n:

public static int f(int i){if(j == 1)return 1;elsereturn i+f(i-1);}

六 1-2+3-4+5…+n:

public static int f(int x){if (x == 1)return 1;else{if (x % 2 == 0){return (-x) + f(x - 1);}else{return x + f(x - 1);}}}

七 一个人赶着鸭子去每个村庄卖,每经过一个村子卖去所赶鸭子的一半又一只。这样他经过了七个村子后还剩两只鸭子,问他出发时共赶多少只鸭子?经过每个村子卖出多少只鸭子?

public static int f(int x, int sum){if (x > 0){sum = 2 * sum + 2;if (x - 1 > 0){Console.WriteLine(\"第\" + (x - 1) + \"个村庄 卖出\" + (2 * sum + 2 - sum));}x--;return f(x, sum);}else{Console.WriteLine(\"一共\" + (sum) + \"只\");return sum;}}
赞(0) 打赏
未经允许不得转载:爱站程序员基地 » c# 常用递归算法(斐波那契数列,阶乘,猴子选大王)等