Fibonacci数列
2014-02-16 00:28
218 查看
在正常情况下,考虑到编程规范,我们可以这样写Fibbonacci:
如果纯粹是一道简单的ACM题,则可以先把第1项到题目限制项的Fibonacci数求出来,放到向量里,直接查表即可,这样不会超时。
还可以这样写(关键是不要重复计算):
#include<iostream> #include<fstream> #include<vector> #include<iterator> #include<algorithm> #include<functional> using namespace std; const vector<long long int>* fibon_seq(int); bool fibon_elem(int, long long int&); int main() { int pos(0); cout << "Fibonacci: Please input a position(1-729):\n"; long long int elem(0); while (cin >> pos) { if (fibon_elem(pos, elem)) { cout << "element # " << pos << " is " << elem << endl; } else { cout << "Sorry.Couldn not calculate the element # " << pos << endl; } } system("pause"); return 0; } //产生Fibonacci序列,第1,2,3个数分别为1,1,2. const vector<long long int>* fibon_seq(int size) { //Fibonacci序列第730个数超过long long int 的表示范围 const int maxSize = 729; static vector<long long int> elems; if (size <= 0 || size>maxSize) { cerr << "fibcon_seq():oops,invalid size. " << size << "--can not fulfill the request.\n"; return 0; } //如果size小于elems.size(),就不用计算了 for (int ix = elems.size(); ix < size; ix++) { if (ix == 0 || ix == 1) elems.push_back(1); else elems.push_back(elems[ix - 2] + elems[ix - 1]); } if (size == 1 || size) return &elems; } //返回Fibonacci 数列中位置为 pos 的元素(位置从1开始) bool fibon_elem(int pos, long long int &elem) { const vector<long long int>* pseq = fibon_seq(pos); if (!pseq) { elem = 0; return false; } elem = (*pseq)[pos - 1]; return true; }注意:long long int 不能在vc6.0中正常编译运行,需改为 _int64. 有关 long long int 与 _int64 在不同编译器上的区别请参考其他文章。
如果纯粹是一道简单的ACM题,则可以先把第1项到题目限制项的Fibonacci数求出来,放到向量里,直接查表即可,这样不会超时。
#include<iostream> #include<fstream> #include<vector> #include<iterator> #include<algorithm> #include<functional> using namespace std; int main() { ifstream cin("D:\\data.txt"); const int maxSize = 50; vector<int> fib_seq; fib_seq.push_back(1); fib_seq.push_back(1); for (int i = 2; i < maxSize; i++) { fib_seq.push_back(fib_seq[i - 2] + fib_seq[i - 1]); } int n(0); //直接输出Fibonacci序列,从1开始计算 while(cin >> n) { cout << fib_seq[n - 1] << endl; } system("pause"); return 0; }
还可以这样写(关键是不要重复计算):
int fib(int n) { int prev=1,next=1,tmp=2; for(int i = 2; i <= n; i++){ tmp = prev + next; prev = next; next = tmp; } return tmp; }
相关文章推荐
- Fibonacci数列
- c#扩展方法奇思妙用变态篇一:由Fibonacci数列引出“委托扩展”及“递推递归委托”
- 基于fibonacci数列的几种编程语言的运算速度比较
- 请用递归算法,求Fibonacci数列。
- 【转帖】O(logn)求Fibonacci数列
- Fibonacci数列的递归与非递归实现
- Fibonacci数列递归 + 数组缓存算法
- 程序员面试题100题第16题——O(logN)求Fibonacci数列
- 数组 Fibonacci数列
- Fibonacci数列的各种解法
- NOJI 148 fibonacci数列(二) 矩阵乘法二分幂
- 又见fibonacci数列(斐波纳契)
- 算法习题19:Fibonacci数列深入
- Fibonacci数列 递归实现
- 第6周作业3-Fibonacci数列
- 第6周作业3-Fibonacci数列
- 经典算法之Fibonacci数列
- fibonacci数列(tyvj 1337)
- Fibonacci数列的各种解法