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.
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.
大数好久没接触 ,还没有记模板,比赛的时候推了一个小时(用char)
刚开始提交是空间超限,然后改了下数组大小,就可以了。
代码:
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#include<iostream>
char h [7100][2015];
void dashu(int i)
{
int e=0;
for(int j=0; j<=2005; j++)
{
h[i][j]=(h[i-1][j]-'0')+(h[i-2][j]-'0')+(h[i-3][j]-'0')+(h[i-4][j]-'0')+e+'0';
e=(h[i][j]-'0')/10;
h[i][j]=(h[i][j]-'0')%10+'0';
}
return ;
}
int main()
{
int n;
memset(h,'0',sizeof(h));
h[1][0]=h[2][0]=h[3][0]=h[4][0]='1';
for(int i=5; i<7100; i++)
dashu(i);
while(~scanf("%d",&n))
{
int j=2005;
while(h[n][j]=='0')
j--;
for(int k=j; k>=0; k--)
printf("%c",h[n][k]);
printf("\n");
}
}
发现好多朋友用的int都超限了,因为int是四个字节,char是一个字节,尽管char操作起来比较复杂,但是相当节省内存,不过用short int有时也可也卡过去,或者用int存多位数。。。
意外发现,用int存八位数空间时间都比char要快。。
#include<stdio.h>
#include<string.h>
#include<algorithm>
#define N 2010
int a[7061][260];
int i,n,m,j,k,l;
int main()
{
memset(a,0,sizeof(a));
a[1][0]=a[2][0]=a[3][0]=a[0][0]=1;
for(i=4;i<7060;i++)
{
k=0;
for(j=0;j<=251;j++)
{
a[i][j]=a[i-1][j]+a[i-2][j]+a[i-3][j]+a[i-4][j]+k;
k=a[i][j]/100000000;
a[i][j]=a[i][j]%100000000;
}
}
while(scanf("%d",&n)!=EOF)
{
j=251;
while(a[n-1][j]==0)
j--;
printf("%d", a[n-1][j--]);
for(; j>=0; j--)
printf("%.8d", a[n-1][j]);//剩下的一定是8位数的,所以输出%.8d
putchar('\n');
}
return 0;
}