博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

ZOJ_1828 Fibonacci Numbers 费波纳奇数列

Posted on 2010-08-24 21:49  还好  阅读(1055)  评论(0编辑  收藏  举报
Fibonacci Numbers

Time Limit: 1 Second      Memory Limit: 32768 KB

A 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 Input

100


Sample Output

354224848179261915075


Note:

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>
using namespace std;

void Add(int*a, int len1,int* b, int len2)//两个大整数求和,和保存在数组a中
{
    
int i,sum;
    
int min=len1<=len2?len1:len2;
    
for(i=0;i<min;i++)
    {
        sum
=a[i]+b[i];
        
if(sum>=10)
        {
            a[i]
=sum-10;
            a[i
+1]++;
        }
        
else
        {
            a[i]
=sum;
        }
    }
}

void Print(int*c, int len)
{
    
int i;
    
for(i=len-1;i>=0;i--)
    {
        
if(c[i]!=0)break;
    }
    
for(;i>=0;i--)
    {
        cout
<<c[i];
    }
    cout
<<endl;
}


int main(void)
{
    
int* a=new int[1000];
    
int* b=new int[1000];
    
int *temp;
    
int i,n;
    
while(cin>>n)
    {
        a[
0]=1;
        b[
0]=1;
        
for(i=1;i<1000;i++)a[i]=b[i]=0;
        
for(i=3;i<=n;i++)
        {
            Add(a,
1000,b,1000);
            temp
=a;
            a
=b;
            b
=temp;
        }
        Print(b,
1000);
    }
}