对于数组中的大数加法 为了节省内存 可以考虑使用滚动数组
杭电1250
Problem Description
A Fibonacci sequence is calculated by adding the previous two members the sequence, with the first two members being both 1.
F(1) = 1, F(2) = 1, F(3) = 1,F(4) = 1, F(n>4) = F(n - 1) + F(n-2) + F(n-3) + F(n-4)
Your task is to take a number as input, and print that Fibonacci number.
F(1) = 1, F(2) = 1, F(3) = 1,F(4) = 1, F(n>4) = F(n - 1) + F(n-2) + F(n-3) + F(n-4)
Your task is to take a number as input, and print that Fibonacci number.
Input
Each line will contain an integers. Process to end of file.
Output
For each case, output the result in a line.
Sample Input
100
Sample Output
4203968145672990846840663646
Note:
No generated Fibonacci number in excess of 2005 digits will be in the test data, ie. F(20) = 66526 has 5 digits.
这题的位数为2005 如果硬开数组的 很容易超内存
在讨论区里面看到一个滚动数组的使用 可以有效的节省内存 此题实际要用的行数只有5个 无非是五个数的循环使用 更新 在对 i遍历的时候 i%5可以控制值一直在0 到 5 之间循环 每次对一个行进行运算之前 先清空数组 然后再附值
实际就是数据的更新过程
上代码
#include<iostream>
#include<cstring>
using namespace std;
short x[5][2008];
int main()
{
int n,i,j,sum,add;
while(cin>>n)
{
if(n<=4)
{
cout<<1<<endl;
continue;
}
memset(x,0,sizeof(x));
x[1][2005]=1;
x[2][2005]=1;
x[3][2005]=1;
x[4][2005]=1;
for(i=5;i<=n;++i)
{
memset(x[i%5],0,sizeof(x[i%5])); //注意清零。
add=0;
for(j=2005;j>=0;j--)
{
sum=x[(i-1)%5][j]+x[(i-2)%5][j]+x[(i-3)%5][j]+x[(i-4)%5][j]+add;
add=sum/10;
x[i%5][j]=sum%10;
}
}
for(i=0;i<=2005;i++)
{
if(x[n%5][i]!=0) break;
}
for(j=i;j<=2005;j++)
cout<<x[n%5][j];
cout<<endl;
}
return 0;
}