Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit af2c559

Browse files
Learning DP
1 parent 135eabc commit af2c559

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed

‎src/FIBOSUM.java‎

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
//SPOJ
2+
/*
3+
*
4+
* INTERESTING FORMULA LEARNED
5+
* BINET'S FORMULA FOR SUM OF A RANGE OF FIBONACCI NUMBERS
6+
*
7+
* S(N) = F(N+2) - 1 ;
8+
*
9+
* AND
10+
*
11+
* S(L,R) = F(R+2) - F(L+1) ;
12+
*
13+
*
14+
*
15+
*
16+
* */
17+
18+
import java.io.*;
19+
20+
public class FIBOSUM {
21+
22+
static long MOD = 1000000007;
23+
public static void main(String[] args)throws IOException {
24+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
25+
26+
int t = Integer.parseInt(br.readLine());
27+
while(t-- > 0) {
28+
String[] s = br.readLine().split(" ");
29+
long n = Long.parseLong(s[0]);
30+
long m = Long.parseLong(s[1]);
31+
m+=2;
32+
n+=1;
33+
34+
35+
m--;
36+
long[][] M = {{1,1},{1,0}};
37+
long[][] IdentityM = {{1,0},{0,1}};
38+
39+
while(m > 0){
40+
if((m & 1) == 1){
41+
IdentityM = multiply(IdentityM,M);
42+
}
43+
M = multiply(M,M);
44+
m = m >> 1;
45+
}
46+
47+
long ansM = (IdentityM[0][0])%MOD;
48+
49+
n--;
50+
long[][] N = {{1,1},{1,0}};
51+
long[][] IdentityN = {{1,0},{0,1}};
52+
53+
while(n > 0){
54+
if((n & 1) == 1){
55+
IdentityN = multiply(IdentityN,N);
56+
}
57+
N = multiply(N,N);
58+
n = n >> 1;
59+
}
60+
61+
long ansN = (IdentityN[0][0])%MOD;
62+
long sum = (ansM - ansN + MOD)%MOD;
63+
64+
System.out.println(sum);
65+
66+
}
67+
}
68+
69+
private static long[][] multiply(long[][] A,long[][] B){
70+
long a = (A[0][0]*B[0][0] + A[0][1]*B[1][0])%MOD;
71+
long b = (A[0][0]*B[0][1] + A[0][1]*B[1][1])%MOD;
72+
long c = (A[1][0]*B[0][0] + A[1][1]*B[1][0])%MOD;
73+
long d = (A[1][0]*B[0][1] + A[1][1]*B[1][1])%MOD;
74+
75+
A[0][0] = a;
76+
A[0][1] = b;
77+
A[1][0] = c;
78+
A[1][1] = d;
79+
80+
return A;
81+
}
82+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /