C++ optimized fib function via map

 1 #include <iostream>
 2 #include <map>
 3 
 4 using namespace std;
 5 
 6 map<int, unsigned long long> fibMap;
 7 unsigned long long fibDemo4(int i);
 8 
 9 int main()
10 {
11     for (int i = 1; i < 50; i++)
12     {
13         cout << "i= " << i << ",fib result= " << fibDemo4(i)<< endl;
14     }
15     getchar();
16 }
17 
18 
19 unsigned long long fibDemo4(int i)
20 {
21     map<int, unsigned long long>::iterator itr;
22     itr = fibMap.find(i);
23     if (itr!=fibMap.end())
24     {
25         return itr->second;
26     }
27 
28     if (i == 1 || i==2)
29     {
30         if (i == 1)
31         {
32             fibMap.insert(pair<int, unsigned long long>(1, 1));
33         }
34         else
35         {
36             fibMap.insert(pair<int, unsigned long long>(2, 1));
37         } 
38         return 1;
39     } 
40     else 
41     {
42         unsigned long long result = fibDemo4(i - 2) + fibDemo4(i - 1);
43         fibMap.insert(pair<int, unsigned long long>(i, result));
44         return result;
45     } 
46 }

C++ optimized fib function via map

 

上一篇:华为服务变革转型ITR流程再造的核心精髓许浩明老师一篇文章总结!


下一篇:三维点云学习(Ⅰ)- C++实操