您的位置:首页 > 其它

ZOJ Problem Set–1828 Fibonacci Numbers

2012-05-09 09:23 477 查看
Time Limit: 2 Seconds      Memory Limit: 65536 KBA Fibonacci sequence is calculated by adding the previous two members of the sequence, with the first two members being both 1. f(1) = 1, f(2) = 1, f(n > 2) = f(n - 1) + f(n - 2)Your task is to take a number as input, and print that Fibonacci number.Sample Input100Sample Output354224848179261915075Note:No generated Fibonacci number in excess of 1000 digits will be in the test data, i.e. f(20) = 6765 has 4 digits.Source: University of Waterloo Local Contest 1996.10.05
#include<iostream>
#include<vector>
#include<string>
using namespace std;
const short NUMLENGTH = 1001;
class BigInteger
{
private:
unsigned short *num;
size_t size;
BigInteger& addBigInteger(const BigInteger& pre1, const BigInteger& pre2) const
  {
BigInteger *result = new BigInteger();
size_t loop = pre1.size > pre2.size ? pre1.size:pre2.size;
bool carry = false;//标记运算是否有进位
short tempResult;
size_t i = 0;
for(i = 0; i < loop; i++)
    {
tempResult = *(pre1.num + i)*(i < pre1.size) + *(pre2.num + i)*(i < pre2.size) + (short)carry;
carry = (tempResult >= 10);
*(result->num + i) = tempResult - 10*carry;
}
*(result->num + i) = (short)carry;
result->size = loop + (int)carry;
return *result;
}
public:
BigInteger()
  {
num = new unsigned short[NUMLENGTH];
for(int i = 0; i < NUMLENGTH; i++)
*(this->num + i) = 0;
size = 0;
}
BigInteger(const BigInteger& bi)
  {
num = new unsigned short[NUMLENGTH];
this->size = bi.size;
for(int i = 0; i < NUMLENGTH;i++)
*(this->num + i) = *(bi.num + i);
}
BigInteger(const string& bi)
  {
this->size = bi.length();
num = new unsigned short[NUMLENGTH];
for(int i = size - 1; i >= 0; i--)
    {
*(this->num + i) = bi[i] - '0';
}
for(int j = size; j < NUMLENGTH; j++)
    {
*(this->num + j) = 0;
}
}
BigInteger& operator+(const BigInteger& op) const
  {
return addBigInteger(*this, op);
}
  void printInteger()
  {
for(int i = size - 1; i >= 0; i--)
      cout<<*(num + i);
}
  void printDataArr()
  {
for(int i = 0; i < NUMLENGTH; i++)
      cout<<*(num + i);
}
  ~BigInteger()
  {
    delete [] num;
}
};
int main(void)
{
  vector<BigInteger> fabonacci;
  fabonacci.push_back(BigInteger("0"));
  fabonacci.push_back(BigInteger("1"));
  fabonacci.push_back(BigInteger("1"));
  int num;
  while(cin>>num)
  {
    if(fabonacci.size() <= num)
    {
      for(int i = fabonacci.size() - 1;i < num; i++)
        fabonacci.push_back(fabonacci[i] + fabonacci[i - 1]);
}
    fabonacci[num].printInteger();
    cout<<endl;
}
  return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: