Fibonacci Numbers
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 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).
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
这道题就要用到斐波那契数列的通项公式了
然后求后四位好求,求前四位怎么求呢?
因为长度不一定,所以我们要把第n个数去log:log(n)=log(小数部分)+整数
这时把小数减去在取对数就可以了
也就是把一个数化成x.xxxxx,然后乘1000就行
#include<bits/stdc++.h>
using namespace std;
const int mod=1e9;
using LL= int64_t;
struct matrix {
LL m[2][2];
}ans,base;
matrix multi(matrix a,matrix b) {
matrix temp;
for(int i=0;i<2;i++) {
for(int j=0;j<2;j++) {
temp.m[i][j]=0;
for(int k=0;k<2;k++) {
temp.m[i][j]=(a.m[i][k]*b.m[k][j]+temp.m[i][j])%mod;
}
}
}
return temp;
}
LL fast_mod(int n) {
base.m[0][0]=base.m[0][1]=base.m[1][0]=1;
base.m[1][1]=0;
ans.m[0][0]=ans.m[1][1]=1;
ans.m[0][1]=ans.m[1][0]=0;
while(n) {
if(n&1) ans=multi(ans,base);
base=multi(base,base);
n>>=1;
}
return ans.m[0][1];
}
int main()
{
LL n;
while(cin>>n) {
if(n<=39) cout<<fast_mod(n)<<endl;
else {
double sum=-0.5*log10(5.0)+n*1.0*log10((1+sqrt(5.0))/2.0);
sum-=(LL)sum;
double temp=pow(10,sum)*1000;
cout<<(LL) temp<<"...";
cout.fill('0');
cout.width(4);
cout<<fast_mod(n)%10000<<endl;
}
}
return 0;
}