递归之斐波那契
斐波那契数列 f(0) = 0; f(1) = 1.......f(n) = f(n-1) + f(n - 2)
1 unsigned Fibo(int n) { 2 if (n == 0) 3 return 0; 4 if (n == 1) 5 return 1; 6 return Fibo(n - 1) + Fibo(n - 2); 7 } 8 unsigned Fibo_no_recursion(int n) { 9 int a[200];//数组容量要大于n 10 a[0] = 0; 11 a[1] = 1; 12 for (int i = 2; i <= n; ++i) { 13 a[i] = a[i - 1] + a[i - 2]; 14 } 15 return a[n]; 16 } 17 unsigned Fibo_no_recursion2(int n) { 18 int a,b,result; 19 a = 0; 20 b = 1; 21 if (n == 0) 22 result = 0; 23 else if (n == 1) 24 result = 1; 25 else 26 for (int i = 2; i <= n; ++i) { 27 result = a + b; 28 a = b; 29 b = result; 30 } 31 return result; 32 } 33 int main() { 34 printf("%u\n", Fibo_no_recursion(100)); 35 printf("%u\n", Fibo_no_recursion2(100)); 36 printf("%u\n", Fibo(38));//最慢,比两个非递归的慢的多的多的多 37 system("pause"); 38 return 0; 39 }