In the Fibonacci integer sequence, F0 = 0, F1 = 1, and Fn = Fn − 1 + Fn − 2 for n ≥ 2. For example, the first ten terms of the Fibonacci sequence are:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, …
An alternative formula for the Fibonacci sequence is
Given an integer n, your goal is to compute the last 4 digits of Fn.
Input
The input test file will contain multiple test cases. Each test case consists of a single line containing n (where 0 ≤ n ≤ 1,000,000,000). The end-of-file is denoted by a single line containing the number −1.
Output
For each test case, print the last four digits of Fn. If the last four digits of Fn are all zeros, print ‘0’; otherwise, omit any leading zeros (i.e., print Fn mod 10000).
Sample Input
0
9
999999999
1000000000
-1
Sample Output
0
34
626
6875
这道题的大致意思就是给你一个数字n,让你去求第n个数的斐波那契数位多少。
根据题目所写,这道题我们明显就是要用到矩阵快速幂。这是一道矩阵快速幂的经典题。
具体看代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
typedef long long LL;
const int mode=10000;
const int maxn=2;
struct Matrix{
LL m[maxn][maxn];
};
Matrix I={//一开始的fibonacci数列
1,0,
0,1,
};
Matrix Multi(Matrix a,Matrix b){
Matrix res;
for(int i=0;i<maxn;i++){
for(int j=0;j<maxn;j++){
res.m[i][j] = 0;
for(int k=0;k<maxn;k++){
res.m[i][j]=(res.m[i][j]+a.m[i][k]*b.m[k][j])%mode;
}
}
}
return res;
}
Matrix quick(Matrix a,LL n){
Matrix ans=I;
while(n)
{
if(n&1)ans=Multi(ans,a);
a=Multi(a,a);
n>>=1;
}
return ans;
}
int main(){
LL n;
while(cin>>n){
if(n==-1)break;
Matrix A={
1,1,
1,0,
};
Matrix x=quick(A,n);
printf("%lld\n",x.m[1][0]);
}
}
道阻且长
自己选的路 跪着也要走完