Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 11750 | Accepted: 8341 |
Description
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
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:
.
Source
数论真是神奇到家了~竟然能用矩阵快速幂来完成打表不能完成的东西。这里N非常大,打表很难。暴力不知道能不能过~【没试过应该是会超时的吧】。
所以这里我们用矩阵快速幂来完成这个问题。我问了学长,这个矩阵1 1 1 0是怎么来的呢?学长给了我一个式子让我恍然大悟:
(??)乘(F【n】)======》(F【n+1】)
(??) (F【n-1】) (F【n】 )
这里我们知道斐波那契数列的性质:Fn=fn-1+fn-2;
所以我们就能够根据矩阵乘法向?上填数。
这样我们就能得到:
(1 1)
(1 0)的矩阵了
这里我们矩阵快速幂和数据快速幂是一样的理论,只不过那里的tmp是1,这里的tmp是单位矩阵。
这里我们直接上代码:
#include<stdio.h>
#include<iostream>
#include<string.h>
using namespace std;
#define mod 10000
typedef struct Matrix
{
int mat[2][2];
}matrix;
matrix A,B;
Matrix matrix_mul(matrix a,matrix b)矩阵乘法
{
matrix c;
memset(c.mat,0,sizeof(c.mat));
int i,j,k;
for(int i=0;i<2;i++)
{
for(int j=0;j<2;j++)
{
for(int k=0;k<2;k++)
{
c.mat[i][j]+=a.mat[i][k]*b.mat[k][j];
c.mat[i][j]%=mod;
}
}
}
return c;
}
Matrix matrix_quick_power(matrix a,int k)//矩阵快速幂0.0
{
matrix b;
memset(b.mat,0,sizeof(b.mat));
for(int i=0;i<2;i++)
b.mat[i][i]=1;//单位矩阵b
while(k)
{
if(k%2==1)
{
b=matrix_mul(a,b);
k-=1;
}
else
{
a=matrix_mul(a,a);
k/=2;
}
}
return b;
}
int main()
{
int n;
while(cin>>n)
{
if(n==-1)break;
A.mat[0][0]=1;A.mat[0][1]=1;//我们通过推论得到的矩阵A
A.mat[1][0]=1;A.mat[1][1]=0;
B=matrix_quick_power(A,n);
cout<<B.mat[0][1]<<endl;//根据推论得出,这个位子上的数据是我们最终需要的数据。
/*for(int i=0;i<2;i++)
{
for(int j=0;j<2;j++)
{
cout<<B.mat[i][j]<<" ";
}
cout<<endl;
}*/
}
}