POJ 3070 - Fibonacci (矩阵快速幂)
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
Solution
将斐波那契数列用下图方法表示出来,然后取右上角即可。
Code
#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
#define maxn 3
typedef long long ll;
struct Mat
{
int mat[maxn][maxn];//矩阵
int row, col;//矩阵行列数
};
Mat mod_mul(Mat a, Mat b, int p)//矩阵乘法
{
Mat ans;
ans.row = a.row;
ans.col = b.col;
memset(ans.mat, 0, sizeof(ans.mat));
for (int i = 1;i<=ans.row;i++)
for (int j = 1;j<=ans.col;j++)
for (int k = 1;k<=a.col;k++)
{
ans.mat[i][j] += a.mat[i][k] * b.mat[k][j];
ans.mat[i][j] %= p;
}
return ans;
}
Mat mod_pow(Mat a, int k, int p)//矩阵快速幂
{
Mat ans;
ans.row = a.row;
ans.col = a.col;
for (int i = 1;i <= a.row;i++)
for (int j = 1;j <= a.col;j++)
ans.mat[i][j] = (i == j);
while (k)
{
if (k & 1)ans = mod_mul(ans, a, p);
a = mod_mul(a, a, p);
k >>= 1;
}
return ans;
}
int main()
{
int n;
Mat A;
A.mat[1][1] = 1; A.mat[1][2] = 1;
A.mat[2][1] = 1; A.mat[2][2] = 0;
A.row = A.col = 2;
while (scanf("%d",&n)&&n!=-1)
{
Mat ans = mod_pow(A, n, 10000);
printf("%d\n", ans.mat[1][2]);
}
return 0;
}