您的位置:首页 > 其它

Fibonacci数列

2014-02-16 00:28 218 查看
在正常情况下,考虑到编程规范,我们可以这样写Fibbonacci:

#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: