zoj1828 Fibonacci Numbers
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.
结题思路
斐波那契+大数计算
斐波那契采用查表方式
大数计算采用数组进行计算
#include <stdio.h>
#include<string.h>
#define MAX_NUM 4900 //经测试,第4900个数时,结果位数为1024位
#define MAX_DIGIT 1100 //本题中需保证每一个结果都可以在数组中存储,因此至少为1024
int len_ans;
int table[MAX_NUM][MAX_DIGIT];//菲波那契表
int len_table[MAX_NUM];//菲波那契表中每个数据长度
void ladd(int a[],int len_a,int b[],int len_b,int t){//大数加法,t为表中位置
int n;
int i;
int flag=0;//进位标志
n=len_a<len_b?len_a:len_b;
for(i=0;i<n;i++){
table[t][i]=a[i]+b[i]+flag;
if(flag=table[t][i]/10) {
table[t][i] = table[t][i] % 10;
}
}
while(n<len_a){
table[t][n]=a[n]+flag;
if(flag=table[t][n]/10){
table[t][n]=table[t][n]%10;
}
n++;
}
while(n<len_b){
table[t][n]=b[n]+flag;
if(flag=table[t][n]/10){
table[t][n]=table[t][n]%10;
}
n++;
}
if(flag){
table[t][n++]=flag;
}
len_ans=n;
}
int main(){
int n;
int i,j;
table[1][0]=1;
len_table[1]=1;
table[2][0]=1;
len_table[2]=1;
for(i=3;i<MAX_NUM;i++){
ladd(table[i-2],len_table[i-2],table[i-1],len_table[i-1],i);
len_table[i]=len_ans;
}
// for(i=1;i<MAX_NUM;i++){//打印数据
// printf("%d--",i);
// for(j=len_table[i]-1;j>=0;j--){
// printf("%d",table[i][j]);
// }
// printf("\n");
// printf("%d\n",len_table[i]);
// }
while(scanf("%d",&n)!=EOF)
{
for(i=len_table[n]-1;i>=0;i--){
printf("%d",table[n][i]);
}
printf("\n");
}
return 0;
}
注意:
本题有多个测试用例