Fibonacci 1

来源:互联网 发布:如何用信用卡支付淘宝 编辑:程序博客网 时间:2024/05/14 06:57
The Fibonacci sequence is the sequence of numbers such that every element is equal to the sum of the two previous elements, except for the first two elements f0 and f1 which are respectively zero and one.
What is the numerical value of the nth Fibonacci number?
Input
For each test case, a line will contain an integer i between 0 and 108 inclusively, for which you must compute the ith Fibonacci number fi. Fibonacci numbers get large pretty quickly, so whenever the answer has more than 8 digits, output only the first and last 4 digits of the answer, separating the two parts with an ellipsis (“...”). There is no special way to denote the end of the of the input, simply stop when the standard input terminates (after the EOF). 
Output
0112359227465149303522415781739088169632459861023...41551061...77231716...7565
Sample Input
0123453536373839406465
Sample Output
0112359227465149303522415781739088169632459861023...41551061...77231716...7565
题意:求Fibonacci前四位和后四位
题解:前四位可以用Fibonacci通项求出
后四位通过快速矩阵幂(每次对10000取余)
#include"stdio.h"#include"cstdio"#include"string.h"#include"math.h"#include"algorithm"using namespace std;typedef long long ll;struct mat{ll m[5][5];};mat multi(mat X,mat Y){mat Z;ll i,j,c;for(i=0;i<2;i++){for(j=0;j<2;j++){c=0;for(int k=0;k<2;k++)c+=X.m[i][k]*Y.m[k][j]%10000;c=c%10000;Z.m[i][j]=c;}}return Z;}ll fab(mat A,int n){ll i,j;mat B;B.m[0][0]=1;B.m[1][1]=1;B.m[0][1]=0;B.m[1][0]=0;while(n){if(n&1) B=multi(B,A); A=multi(A,A);n>>=1;}return B.m[1][1];}int main(){int n;ll f[50];f[0]=0;f[1]=1;for(int i=2;i<45;i++){f[i]=f[i-1]+f[i-2];}while(scanf("%d",&n)!=EOF){mat A;for(int i=0;i<2;i++){for(int j=0;j<2;j++)A.m[i][j]=1;}ll ret;A.m[0][0]=0;if(n>=40)ret=fab(A,n-1);if(n<=39)printf("%lld\n",f[n]);else{double ans=log10(1.0/sqrt(5))+(double)n*log10((1+sqrt(5))/2.0);int ret1=(int)pow(10.0,(ans-int(ans)+3));printf("%d...",ret1);ret=ret%10000;printf("%04lld\n",ret);}}}



原创粉丝点击