ZOJ Problem Set - 1828
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.
1 #include<iostream> 2 using namespace std; 3 int a[6001][1001]; 4 int getmaxlen(int fir,int sec) 5 { 6 int i,j; 7 for(i=1000;a[fir][i]==0;i--); 8 for(j=1000;a[sec][j]==0;j--); 9 if(i>=j) 10 return i; 11 else 12 return j; 13 } 14 void fibonacci(int n) 15 { 16 int i,j,len; 17 int c=0; 18 for(j=2;j<n;j++) 19 { 20 len=getmaxlen(j-1,j-2); 21 for(i=0;i<=len+1;i++) 22 { 23 a[j][i]=(a[j-1][i]+a[j-2][i]+c)%10; 24 c=(a[j-1][i]+a[j-2][i]+c)/10; 25 } 26 } 27 } 28 int main() 29 { 30 int n,i,j; 31 memset(a,0,sizeof(a)); 32 a[0][0]=1; 33 a[1][0]=1; 34 while(cin>>n) 35 { 36 for(i=1000;a[n-1][i]==0;i--); 37 if(i<0) 38 { fibonacci(n); 39 for(i=1000;a[n-1][i]==0;i--); 40 } 41 for(j=i;j>=0;j--) 42 cout<<a[n-1][j]; 43 cout<<endl; 44 } 45 return 0; 46 }
注:不能直接用公式,因为当数较大时用int型无法表示,这里一位一位计算,然后存储到数组中,最后输出。