简单数论之矩阵构造

其实矩阵构造就是对公式的化简,最后运用矩阵快速幂求值

下面来看一题

Everybody knows Fibonacci numbers, now we are talking about the Tribonacci numbers: T[0] = T[1] = T[2] = 1; T[n] = T[n - 1] + T[n - 2] + T[n - 3] (n >= 3)
Given a and b, you are asked to calculate the sum from the ath Fibonacci number to the bth Fibonacci number, mod 1,000,000,007, that is (T[a] + T[a + 1] + ... + T[b]) % 1,000,000,007.
There are multiple cases (no more than 100).
Each case contain two non-negative integers a b(a <= b and a, b < 1,000,000,000)
For each case, output the sum % 1,000,000,007.
T[n] = T[n - 1] + T[n - 2] + T[n - 3]
左边累加,右边累加我们发现
sum[n] = sum[n - 1] + sum[n - 2] + sum[n - 3]
 1  1  1
 1  0  0
 0  1  0
 
sum[n-1]  0   0
sum[n-2]  0   0
sum[n-3]  0   0
代码:
 #include<iostream>
#include<cstdio>
using namespace std;
#define M 1000000007
struct mat
{
    int ans[4][4];
};
mat I,MID;
mat cal(mat a,mat b)
{
    mat c;
    int i,j,k;
    for(i=0;i<4;i++)
        for(j=0;j<4;j++)
        {
            c.ans[i][j]=0;
            for(k=0;k<4;k++)
                c.ans[i][j]+=a.ans[i][k]*b.ans[k][j];
                c.ans[i][j]%=M;
        }
    return c;
}
mat atl(int n)
{
    mat res=MID;
    mat mid=I;
    while(n){
    if(n&1)
        res=cal(res,mid);
        mid=cal(mid,mid);
        n>>=1;}
        return res;
}
int main()
{
    int k,i,j;
    int a,b;
    while(scanf("%d%d",&a,&b)!=-1)
    {
            I.ans[0][0]=1;
            I.ans[0][1]=1;
            I.ans[0][2]=1;
            MID.ans[0][0]=1;
            MID.ans[0][1]=1;
            MID.ans[0][2]=1;
            MID.ans[1][0]=1;
            MID.ans[2][1]=1;
                mat l=atl(b-2);
                mat g=atl(a-3);
        printf("%d\n",l.ans[0][0]-g.ans[0][0]);
    }
    return 0;
}

posted on 2015-04-04 09:59  AC_WQYYY  阅读(167)  评论(0编辑  收藏  举报

导航