斐波那楔函数最直接的解法是通过递推公式得到的公式
1
#include
<
iostream
>
2
3 using namespace std;
4
5 int Fibonacci( int n)
6 {
7 if (n == 0 || n == 1 )
8 return n;
9 else
10 {
11 return (Fibonacci(n - 1 ) + Fibonacci(n - 2 ));
12 }
13 }
14
15
16 int Fibonacci_t( int n)
17 {
18 int priv1 = 1 , priv2 = 0 , current;
19 if (n < 2 )
20 return n;
21
22 else
23 {
24 for ( int i = 2 ; i <= n; i ++ )
25 {
26 current = priv1 + priv2;
27 priv2 = priv1;
28 priv1 = current;
29 }
30
31 return current;
32 }
33 }
34
35 int Ackerman( int m, int n)
36 {
37 if (m == 0 )
38 return n + 1 ;
39 else if (n == 0 )
40 return Ackerman(m - 1 , 1 );
41 else
42 {
43 return Ackerman(m - 1 , Ackerman(m, n - 1 ));
44 }
45
46
47 }
48
49 int main()
50 {
51 int i, j;
52
53 for (i = 0 ; i < 10 ; i ++ )
54 {
55 cout << Fibonacci(i) << " " ;
56 }
57
58 cout << endl;
59
60 for (i = 0 ; i < 10 ; i ++ )
61 {
62 cout << Fibonacci_t(i) << " " ;
63 }
64
65 cout << endl;
66
67 for (i = 0 ; i < 5 ; i ++ )
68 for (j = 0 ; j < 5 ; j ++ )
69 {
70 cout << Ackerman(i, j) << " " ;
71 }
72
73 return 0 ;
74 }
75
2
3 using namespace std;
4
5 int Fibonacci( int n)
6 {
7 if (n == 0 || n == 1 )
8 return n;
9 else
10 {
11 return (Fibonacci(n - 1 ) + Fibonacci(n - 2 ));
12 }
13 }
14
15
16 int Fibonacci_t( int n)
17 {
18 int priv1 = 1 , priv2 = 0 , current;
19 if (n < 2 )
20 return n;
21
22 else
23 {
24 for ( int i = 2 ; i <= n; i ++ )
25 {
26 current = priv1 + priv2;
27 priv2 = priv1;
28 priv1 = current;
29 }
30
31 return current;
32 }
33 }
34
35 int Ackerman( int m, int n)
36 {
37 if (m == 0 )
38 return n + 1 ;
39 else if (n == 0 )
40 return Ackerman(m - 1 , 1 );
41 else
42 {
43 return Ackerman(m - 1 , Ackerman(m, n - 1 ));
44 }
45
46
47 }
48
49 int main()
50 {
51 int i, j;
52
53 for (i = 0 ; i < 10 ; i ++ )
54 {
55 cout << Fibonacci(i) << " " ;
56 }
57
58 cout << endl;
59
60 for (i = 0 ; i < 10 ; i ++ )
61 {
62 cout << Fibonacci_t(i) << " " ;
63 }
64
65 cout << endl;
66
67 for (i = 0 ; i < 5 ; i ++ )
68 for (j = 0 ; j < 5 ; j ++ )
69 {
70 cout << Ackerman(i, j) << " " ;
71 }
72
73 return 0 ;
74 }
75