n 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 Fnare 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
Hint
As a reminder, matrix multiplication is associative, and the product of two 2 × 2 matrices is given by
.
Also, note that raising any 2 × 2 matrix to the 0th power gives the identity matrix:
.
按题意所给的构造的矩阵求解:
代码:
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
const int N=5;
struct mat{
int m[N][N];
}init;
void Init()
{
init.m[0][0]=1;
init.m[0][1]=1;
init.m[1][0]=1;
init.m[1][1]=0;
}
mat Mul(mat a,mat b)
{
mat c;
memset(c.m,0,sizeof(c.m));
for(int i=0;i<2;i++)
for(int j=0;j<2;j++)
{
for(int k=0;k<2;k++)
c.m[i][j]+=a.m[i][k]*b.m[k][j];
c.m[i][j]%=10000;
}
return c;
}
mat quickpow(mat a,int k)
{
mat res;
memset(res.m,0,sizeof(res.m));
for(int i=0;i<2;i++) res.m[i][i]=1;
while(k)
{
if(k&1) res=Mul(a,res);
a=Mul(a,a);
k>>=1;
}
return res;
}
int main()
{
int n;
while(cin>>n&&n!=-1)
{
Init();
mat t=quickpow(init,n);
cout<<t.m[0][1]%10000<<endl;
}
return 0;
}
常规思路:
矩阵快速幂是用来求解递推式的,所以第一步先要列出递推式:
f(n)=f(n-1)+f(n-2)
第二步是建立矩阵递推式,找到转移矩阵:
,简写成T * A(n-1)=A(n),T矩阵就是那个2*2的常数矩阵,而
这里就是个矩阵乘法等式左边:1*f(n-1)+1*f(n-2)=f(n);1*f(n-1)+0*f(n-2)=f(n-1);
这里还是说一下构建矩阵递推的大致套路,一般An与A(n-1)都是按照原始递推式来构建的,当然可以先猜一个An,主要是利用矩阵乘法凑出矩阵T,第一行一般就是递推式,后面的行就是不需要的项就让与其的相乘系数为0。矩阵T就叫做转移矩阵(一定要是常数矩阵),它能把A(n-1)转移到A(n);然后这就是个等比数列,直接写出通项:此处A1叫初始矩阵。所以用一下矩阵快速幂然后乘上初始矩阵就能得到An,这里An就两个元素(两个位置),根据自己设置的A(n)对应位置就是对应的值,按照上面矩阵快速幂写法,res[1][1]=f(n)就是我们要求的。