Fibonacci数列

在正常情况下,考虑到编程规范,我们可以这样写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;      
}  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值