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 
#include 
#include 
#include 
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;ifor (int j = 1;jfor (int k = 1;kreturn 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 for (int j = 1;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;
}

本博客所有内容采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可

转载文章请注明:POJ 3070 – Fibonacci (矩阵快速幂) - https://blog.i-ll.cc/archives/63

分类: Coding

Vectors

Vectors

不知所措,才是人生。

发表评论

电子邮件地址不会被公开。 必填项已用*标注

我不是机器人*