使用了4种方法求解Fabonacci数列,代码如下:(假设数列为 0 1 1 2 3 5 ……)注意第一项以0开始
1 #include <iostream>
2 #include <time.h>
3 #include <math.h>
4 using namespace std;
5
6 //递归求解
7 int fib_recursion( int n )
8 {
9
10 if( n==0 ) return 0;
11 if( n==1 ) return 1;
12
13 return fib_recursion(n-1) + fib_recursion(n-2);
14 }
15
16 //使用数组存放数列中的每一个值
17 int fib_mem( int n )
18 {
19 int mem[1000];
20 mem[0] = 0;
21 mem[1] = 1;
22
23 for ( int i=2; i<=n; ++i)
24 {
25 mem[i] = mem[i-1]+mem[i-2];
26 }
27
28 return mem[n];
29 }
30 //动态规划
31 int fib_dp( int n )
32 {
33 int first = 0;
34 int second = 1;
35 int sum ;
36
37 for ( int i=0; i<n-1; ++i)
38 {
39 sum = first + second;
40 first = second;
41 second = sum;
42 }
43 return sum;
44 }
45 //binet给出了一个公式可以计算数列,比任何动态规划算法都快,但是这样的公式可欲不可求
46 int fib_binet( int n)
47 {
48 return ( pow( (1+pow(5,0.5)),n ) - pow( (1-pow(5,0.5)),n ))/(pow(2.0,n)*pow(5,0.5));
49 }
50 //测试代码
51 int main()
52 {
53 int n = 30;
54 clock_t timebegin, timeend;
55
56 timebegin = clock();
57 int sum_recursion = fib_recursion(n);
58 timeend = clock();
59 cout << "sum_recursion = " << sum_recursion << " 用时" <<timeend-timebegin << endl;
60
61 timebegin = clock();
62 int sum_mem = fib_mem(n);
63 timeend = clock();
64 cout << "sum_mem = " << sum_mem << " 用时" <<timeend-timebegin << endl;
65
66 timebegin = clock();
67 int sum_dp = fib_dp(n);
68 timeend = clock();
69 cout << "sum_dp = " << sum_dp << " 用时" <<timeend-timebegin << endl;
70
71 int sum_binet = fib_binet(n);
72 cout << "sum_binet= " << sum_binet <<endl;
73
74 return 0;
75 }