Fibonacci Numbers
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 2562 Accepted Submission(s): 1069
Problem Description
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?
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 10
8 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).
There is no special way to denote the end of the of the input, simply stop when the standard input terminates (after the EOF).
Sample Input
0 1 2 3 4 5 35 36 37 38 39 40 64 65
Sample Output
0 1 1 2 3 5 9227465 14930352 24157817 39088169 63245986 1023...4155 1061...7723 1716...7565
Source
Recommend
lcy
/*
求斐波那契数N=1e8的前后四位
求前四位:通项公式,取对数,取前四位
后四位:矩阵快速幂
*/
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int mod=10000;
const int maxn=2;
int f[50];
typedef struct node{
int a[maxn][maxn];
node(){
memset(a,0,sizeof(a));
}
}Matrix;
Matrix mul(Matrix x,Matrix y){
Matrix ans;
for(int i=0;i<maxn;i++){
for(int j=0;j<maxn;j++){
for(int k=0;k<maxn;k++){
ans.a[i][j]+=x.a[i][k]*y.a[k][j];
ans.a[i][j]%=mod;
}
}
}
return ans;
}
Matrix quickpow(Matrix x,int a){
Matrix ans;
for(int i=0;i<maxn;i++)
ans.a[i][i]=1;
while(a){
if(a&1)
ans=mul(ans,x);
x=mul(x,x);
a>>=1;
}
return ans;
}
int main()
{
int n;
f[0]=0,f[1]=1;
for(int i=2;i<40;i++){
f[i]=f[i-1]+f[i-2];
// printf("%d\n",f[i]);
}
while(~scanf("%d",&n)){
if(n<40)
printf("%d\n",f[n]);
else{
double temp=(1.0+sqrt(5))/2;
double a=-0.5*log10(5.0)+n*log10(temp);
a-=(int)a;
double ans=pow(10,a);
while(ans<1000)
ans*=10;
printf("%04d",(int)ans);
Matrix one,x;
one.a[0][0]=1;
one.a[0][1]=0;
x.a[0][0]=x.a[0][1]=x.a[1][0]=1;
Matrix aa=quickpow(x,n-1);
aa=mul(aa,one);
printf("...%04d\n",aa.a[0][0]);
}
}
return 0;
}