Fibonacci Numbers
http://acm.hdu.edu.cn/showproblem.php?pid=3117
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 3242 Accepted Submission(s): 1348
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?
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).
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
IPCP 2005 Northern Preliminary for Northeast North-America
题意
斐波拉契数列的前两项为f[0]=0,f[1]=1,给定n求出f[n],当f[n]超过8位数时,以“高四位...低四位”的形式输出。
思路
求低四位用矩阵快速幂,对于求高四位要用到斐波拉契数列的通项公式
当n>49时
设
其中
,k是F(n)的位数
设
又
可得
高四位就可以通过(int)(t*10000)得到
C++代码
#include<iostream>
#include<cstdio>
#include<vector>
#include<cmath>
using namespace std;
typedef long long ll;
typedef vector<int>vec;
typedef vector<vec>mat;
const int mod=10000;
const int N=50;
ll f[N];
mat mul(const mat &a,const mat &b)
{
mat c(a.size(),vec(b[0].size()));
for(int i=0;i<a.size();i++)
for(int j=0;j<b[0].size();j++)
for(int k=0;k<a[0].size();k++)
c[i][j]=(c[i][j]+a[i][k]*b[k][j])%mod;
return c;
}
mat qpow(mat x,int n)
{
mat res(x.size(),vec(x.size()));
for(int i=0;i<res.size();i++) res[i][i]=1;
while(n)
{
if(n&1) res=mul(res,x);
x=mul(x,x);
n>>=1;
}
return res;
}
//打表求出前n个斐波拉契数
void maketable(int n)
{
f[0]=0,f[1]=1;
for(int i=2;i<n;i++) f[i]=f[i-1]+f[i-2];
}
int solve(int n)
{
mat res(2,vec(1));
res[0][0]=1;
res[1][0]=0;
mat temp(2,vec(2));
temp[0][0]=1,temp[0][1]=1;
temp[1][0]=1,temp[1][1]=0;
temp=qpow(temp,n-1);
res=mul(temp,res);
return res[0][0];
}
int first_four(int n)
{
double tmp=(1.0+sqrt(5.0))/2.0;
double m=n*log10(tmp)-log10(sqrt(5.0));
int k=(int)m+1;//斐波那契数列第n项的位数
double t=m-k;
return (int)(pow(10,t)*10000);
}
int main()
{
maketable(N);
int n;
while(~scanf("%d",&n))
{
if(n<N)
{
if(f[n]<100000000)
printf("%lld\n",f[n]);
else
{
int k=(int)log10(f[n])+1;
int e=1;
for(int i=1;i<=k-4;i++) e*=10;
printf("%lld...%04lld\n",f[n]/e,f[n]%10000);
}
}
else
{
printf("%d...%04d\n",first_four(n),solve(n));
}
}
return 0;
}