fibonacci数列的和取余(1)

As we know , the Fibonacci numbers are defined as follows:

 """"

Given two numbers a and b , calculate . """"

Input

The input contains several test cases. Each test case consists of two non-negative integer numbers a and b (0 ≤ a ≤ b ≤1,000,000,000). Input is terminated by a = b = 0.

Output

For each test case, output S mod 1,000,000,000, since S may be quite large.

Sample Input

1 1
3 5
10 1000
0 0

Sample Output

1
16
496035733

#include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;
const long long mod=1e9;

typedef struct
{
  long long m[3][3];
}mat;

mat p={1,1,0,1,0,0,1,0,1},I={1,0,0,0,1,0,0,0,1};

mat calc(mat a,mat b)
{
    int i,j,k;
    mat c;
    for(i=0;i<3;i++)
    for(j=0;j<3;j++)
    {
        c.m[i][j]=0;
       for(k=0;k<3;k++)
      {
        c.m[i][j]+=a.m[i][k]*b.m[k][j]%mod;
      }
      c.m[i][j]%=mod;
    }
    return c;
}

mat matirx(long long n)
{
    mat m=p,b=I;
    while(n>=1)
    {
        if(n&1) b=calc(b,m);
        n>>=1;
        m=calc(m,m);
    }
    return b;
}

int main()
{
    long long a,b;
    mat x,y;
    while(scanf("%lld%lld",&a,&b)==2&&(a+b))
    {
        long long sum=0;
           y=matirx(b);
           sum=sum+(y.m[2][0]+y.m[2][1]+y.m[2][2])%mod;
           if(a>0)
           {
               x=matirx(a-1);
               sum=sum-(x.m[2][0]+x.m[2][1]+x.m[2][2])%mod;
           }
           else
           sum-=1;
           sum=(sum+mod)%mod;
        printf("%lld\n",sum);
    }
    return 0;
}

 

posted @ 2015-08-16 17:52  茶飘香~  阅读(286)  评论(0编辑  收藏  举报