poj3070

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

这道题有两种解法。

  1. 找斐波那契数列关于模数mod的循环节
  2. 矩阵快速幂

本篇博客采用矩阵快速幂来写。

什么是矩阵快速幂呢?(如果不会快速幂 自己百度)

矩阵快速幂只是把a^b%p 的a变成了一个矩阵而已。

个人的板子:

void mul(int p[][2],int g[][2])
{
    memset(a,0,sizeof a);
    for(int k=0;k<2;k++)
        for(int i=0;i<2;i++)
            for(int j=0;j<2;j++)
                a[k][i]=(a[k][i]+p[k][j]*g[j][i])%10000;
    for(int i=0;i<2;i++)    for(int j=0;j<2;j++)    p[i][j]=a[i][j];
}
void qmi(int n)
{
    while(n)
    {
        if(n&1)
        {
            mul(res,g);
        }
        mul(g,g);
        n>>=1;
    }
}

就是快速幂配合矩阵相乘(不会矩阵相乘的自己百度)

AC代码:

#include<iostream>
#include<cstring>
using namespace std;
int n,a[2][2],g[2][2],res[2][2];
void mul(int p[][2],int g[][2])
{
    memset(a,0,sizeof a);
    for(int k=0;k<2;k++)
        for(int i=0;i<2;i++)
            for(int j=0;j<2;j++)
                a[k][i]=(a[k][i]+p[k][j]*g[j][i])%10000;
    for(int i=0;i<2;i++)    for(int j=0;j<2;j++)    p[i][j]=a[i][j];
}
void qmi(int n)
{
    while(n)
    {
        if(n&1)
        {
            mul(res,g);
        }
        mul(g,g);
        n>>=1;
    }
}
int main()
{
    while(cin>>n,n>=0)
    {
        if(!n)  cout<<0<<endl;
        else
        {
            n--;
            res[0][0]=1;
            res[0][1]=1;
            res[1][0]=1;
            res[1][1]=0;
            g[1][1]=0;g[0][1]=g[1][0]=g[0][0]=1;
            qmi(n);
            cout<<res[1][0]<<endl;
        }
    }
    return 0;
}