Hat's Fibonacci
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 5705 Accepted Submission(s): 1898
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.
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.
解题思路:
把以前的斐波那契数列和大数相加的结合解法。也和N!的解法差不多,
1、 先求出第n个数的结果。每四位保存一起(因为数太大,而且,数组开的越大越占内存)。
2、 对10000取余保存。对10000取整进位。循环相加。
3、 要记得删除多余的0;
程序:
#include<stdio.h>
#include<string.h>
#define M 8000
#define N 800 //数组开的太大会占用空间。
long f[M][N];
int main()
{
int n,m,i,j,t;
long k;
while(scanf("%d",&n)!=EOF)
{
// memset(f,0,sizeof(f));
f[0][N-1]=1;
f[1][N-1]=1;
f[2][N-1]=1;
f[3][N-1]=1;
for(i=4;i<n;i++)
{
for(j=N-1,k=0;j>=0;j--) //k要赋初值
{
k=k+f[i-1][j]+f[i-2][j]+f[i-3][j]+f[i-4][j]; //循环依次相加。
f[i][j]=k%10000; //每4个数一起保存;
k=k/10000; // 取整 多余 4 位的进位;
}
}
j=0;
while(f[n-1][j]==0) //删除多余的 0;
j++;
// printf("%d ",j);
printf("%d",f[n-1][j++]);
for(i=j;i<N;i++)
printf("%4.4ld",f[n-1][i]); //4.4是控制输出0的; 例如 123 则输出 0123.
printf("\n");
}
return 0;
}
/*//小程序测试输出格式
#include<stdio.h>
#include<stdlib.h>
int main()
{
int n=1;
printf("%4.4d\n",n);
printf("%04d\n",n);
printf("%4.4lf",(float)n);
system("pause");
return 0;
} */