Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 9992 | Accepted: 7128 |
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
水題。矩陣快速冪練手題。
參考代碼:
#include<cstdio>
#include<iostream>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<string>
#include<vector>
#include<map>
#include<set>
#include<stack>
#include<queue>
#include<ctime>
#include<cstdlib>
#include<iomanip>
#include<utility>
#define pb push_back
#define mp make_pair
#define CLR(x) memset(x,0,sizeof(x))
#define _CLR(x) memset(x,-1,sizeof(x))
#define REP(i,n) for(int i=0;i<n;i++)
#define Debug(x) cout<<#x<<"="<<x<<" "<<endl
#define REP(i,l,r) for(int i=l;i<=r;i++)
#define rep(i,l,r) for(int i=l;i<r;i++)
#define RREP(i,l,r) for(int i=l;i>=r;i--)
#define rrep(i,l,r) for(int i=1;i>r;i--)
#define read(x) scanf("%d",&x)
#define put(x) printf("%d\n",x)
#define ll long long
#define lson l,m,rt<<1
#define rson m+1,r,rt<<11
using namespace std;
int n;
struct mat
{
int d[2][2];
}A,B,E;
mat multi(mat a,mat b)
{
mat ans;
rep(i,0,2)
{
rep(j,0,2)
{
ans.d[i][j]=0;
rep(k,0,2)
{
if(a.d[i][k]&&b.d[k][j])
ans.d[i][j]=(ans.d[i][j]+a.d[i][k]*b.d[k][j])%10000;
}
}
}
return ans;
}
mat quickmulti(mat a,int n)
{
if(n==0) return E;
if(n==1) return a;
mat ans=E;
while(n)
{
if(n&1)
{
n--;
ans=multi(ans,a);
}
else
{
n>>=1;
a=multi(a,a);
}
}
return ans;
}
int main()
{
A.d[0][0]=A.d[0][1]=A.d[1][0]=E.d[0][0]=E.d[1][1]=B.d[0][0]=1;
A.d[1][1]=E.d[0][1]=E.d[1][0]=B.d[0][1]=B.d[1][0]=B.d[1][1]=0;
while(~read(n)&&n!=-1)
{
mat ans=quickmulti(A,n);
ans=multi(ans,B);
printf("%d\n",ans.d[1][0]);
}
}