NEFU 463 Fibs之和
Fibs之和
description |
As we know , the Fibonacci numbers are defined as follows:
F(0)=1,f(1)=1;f(n)=f(n-1)+f(n-2) n>=2;
Given two numbers a and b , calculate S(n)=f(a)+f(a+1)+….+f(b)
|
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(n) mod 1,000,000,000, since S(n) may be quite large.
|
1 /*
2 写于2013年1月16日,
3 矩阵连乘
4 */
5 #include <iostream>
6 #include <stdio.h>
7 #include <math.h>
8 using namespace std;
9 const int mod=1000000000;
10 typedef struct{
11 long long m[3][3];
12 }matrix;
13
14 matrix P={1,1,1,0,1,1,0,1,0};
15 matrix I={1,0,0,0,1,0,0,0,1};
16 matrix matrmul(matrix a,matrix b)//矩阵相乘
17 {
18 matrix c;
19 for(int i=0;i<3;i++)
20 for(int j=0;j<3;j++)
21 {
22 c.m[i][j]=0;
23 for(int k=0;k<3;k++)
24 c.m[i][j]+=((a.m[i][k]%mod)*(b.m[k][j]%mod))%mod;
25 c.m[i][j]%=mod;
26 }
27 return c;
28 }
29 matrix quickpow(int n)//连乘
30 {
31 matrix b=I;
32 matrix m=P;
33 while(n>=1)
34 {
35 if(n&1)
36 b=matrmul(b,m);
37 n=n>>1;
38 m=matrmul(m,m);
39 }
40 return b;
41 }
42 int main()
43 {
44 int a,b;
45 while(scanf("%d%d",&a,&b)!=EOF)
46 {
47 if(a==0&&b==0)
48 break;
49 matrix sa=quickpow(a-1);
50 matrix sb=quickpow(b);
51 //相减有可能出现负数
52 long long sub=(sb.m[0][0]+sb.m[0][1]-sa.m[0][0]-sa.m[0][1])%mod;
53 sub=(sub+mod)%mod;
54 printf("%lld\n",sub);
55 }
56
57 return 0;
58 }