Fibonacci
Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 19397 Accepted: 13420 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:
.
如:在斐波那契数列之中
f[i] = 1*f[i-1]+1*f[i-2] f[i-1] = 1*f[i-1] + 0*f[i-2];
即
所以
就这两幅图完美诠释了斐波那契数列如何用矩阵来实现。
//POJ3070
//快速矩阵幂算法
//fibonacci 由于给出的n特别大,所有常用的遍及行不通,
//通过推导矩阵幂的方程进而更方便实现 ,在mul_mat中注意要求模数据太大了
#include "iostream"
#include "algorithm"
#include "cstdio"
#include"cstring"
#define rep(i,j,k) for(int i=j;i<=k;i++)
const int mod=1e4;
typedef long long LL;
using namespace std;
struct mat
{
LL a[2][2];
};//记得加引号
mat mul_mat(mat &a,mat &b)
{
mat res;
memset(res.a,0,sizeof(res.a));
rep(i,0,1)
rep(j,0,1)
rep(k,0,1)
{
res.a[i][j]=res.a[i][j]+a.a[i][k]*b.a[k][j]%mod;
}
return res;
}
void pow_mat(int n)
{
mat res,a;
a.a[0][0]=a.a[0][1]=a.a[1][0]=1;
a.a[1][1]=0;
//注意尽管结构体是在全局定义的,但是不论是数组还是int都不会被初始化为0
memset(res.a,0,sizeof(res.a));
res.a[0][0]=1,res.a[1][1]=1;
//初始化完毕
while(n)
{
if(n&1) res=mul_mat(a,res);//试过了,在矩阵中对于单位矩阵,换下位置没关系
a=mul_mat(a,a);//如mul_mat(res,a);
n>>=1;
}
cout<<res.a[0][0]%mod<<endl;
}
int main()
{
int n;
while(cin>>n&&n!=-1)
{
if(n==0)
{
cout<<"0"<<endl;
continue;
}
pow_mat(n-1);
}
return 0;
}