用C++编译器优化实现记忆化

如果要实现输出fib(100)%1200007,可以实现用编译器来自动记忆化。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include<iostream>
using namespace std;
template<int x>
struct fib{
static const int val = (fib<x - 1>::val + fib<x - 2>::val) % 1200007;
}
template<>
struct fib<0>{
static const int val = 1;
}
template<>
struct fib<1>{
static const int val = 1;
}
int main(){
cout << fib<100>::val << endl;
return 0;
}

编译器在编译的时候就会对这个进行优化,会非常快速算出来。

【工程代码】

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <iostream>
using namespace std;

template<int x>
struct fib{
static const int val = (fib<x - 1>::val + fib<x - 2>::val) % 1200007;
};

template<>
struct fib<0>{
static const int val = 0;
};

template<>
struct fib<1>{
static const int val = 1;
};

int fib2(int x){
if (x < 2) return x;
else return (fib2(x - 1) + fib2(x - 2)) % 1200007;
}

int fib3(int x){
int a = 0, b = 1,c;
if (x == 0) b = 0;
else if (x == 1) b = 1;
else{
for (int i = 2; i <= x; i++)
{
c = a + b;
a = b;
b = c % 1200007;
}
}
return b;
}

class fib4{
int *nums;
bool *labels;
int n;
int calc(int x){
if (labels[x]) return nums[x];
nums[x] = calc(x - 1) + calc(x - 2);
labels[x] = 1;
return nums[x] % 1200007;
}
public:
fib4(int x){
n = x;
nums = new int [n];
labels = new bool [n];
memset(labels, 0, sizeof(char) * n);
labels[0] = labels[1] = 1;
nums[0] = 0;
nums[1] = 1;
}
int getFib(){
return calc(n);
}
};
int main(){
cout << fib<100>::val << endl;
cout << fib3(100) << endl;
fib4 f = fib4(100);
cout << f.getFib() << endl;
return 0;
}