FIBOSUM - Fibonacci Sum

no tags 

The fibonacci sequence is defined by the following relation:

  • F(0) = 0
  • F(1) = 1
  • F(N) = F(N - 1) + F(N - 2), N >= 2

Your task is very simple. Given two non-negative integers N and M, you have to calculate the sum (F(N) + F(N + 1) + ... + F(M)) mod 1000000007.


The first line contains an integer T (the number of test cases). Then, T lines follow. Each test case consists of a single line with two non-negative integers N and M.


For each test case you have to output a single line containing the answer for the task.


0 3
3 5
10 19



  • T <= 1000
  • 0 <= N <= M <= 109

hide comments
Harsh Vardhan Ladha: 2015-09-06 16:11:18

it is not given that M>=N causing many to get negative and negative MOD problem.
Tweak a little!

satya_jha123: 2015-08-26 14:17:46

i wrote the code for this and i am gettingb negative ans so how do i handle this part

Last edit: 2015-08-26 14:18:37
offson: 2015-08-23 23:11:22

@Babu, if you do sum(M) - sum(N - 1), the latter one can be bigger than the former due to the modulus application. To solve that, just sum 10^9 + 7 to the result while it is negative.

Babu: 2015-07-26 21:37:47

where is the negative modulus coming .
please answer

Rahul Jain: 2015-07-18 20:39:57

@xxbloodysantaxx, Your comment was very helpful to me. Thanks.
Guys, just try taking out a recurrence for S(n) rather than expressing the sum in fibonacci term.... Will make you feel better surely :√) Well, negative modulus costed me 3 WAs

Last edit: 2015-07-18 23:00:59
Ashish: 2015-07-05 08:44:29

Oh never mind. I read it from Wikipedia anyway. Turns out :
summation ( F[i] , n<= i <= m ) = F(m+2) - F(n+1) ( n>= 0 ), so it can be done in O(logm) time only. Use approximation to Binnet's formula:
F(n) = (round) [(Phi)^(n) / sqrt(5)] ; where Phi is the golden ratio.
[ Fib(10^(9)) has 208987640 digits ]

Last edit: 2015-07-06 09:07:42
Ashish: 2015-07-04 19:21:52

What is the link to Rafael Perella's thread? I am getting TLE despite using a O( logn + (m-n) ) algorithm. ( O(logn) to find f(n) and O(m-n) to compute f(i) ( n<=i<=m) and sum, and take modulo. I am even taking modulo at the matrix multiplication step. But I am using a recursive function instead of a loop for the O(logn) part. Is that the reason? plz help.....

14mandeep: 2015-06-23 18:35:23

finally accepted
learnt hell lot of things

Master_Card: 2015-06-23 11:19:51

my 150th :)
Good question!!

r0bo_dart: 2015-06-22 18:13:46

My LOL moment.. loaded 2 times the old code while tweaking the new one. GOT WA 2-3 times i guess :P ... #BEWARE
Hint: Tweak your O(logn) code as @Arjun says. Thanks to you. @Arjun.

Added by:David Gómez
Time limit:1s
Source limit:50000B
Memory limit:1536MB
Cluster: Cube (Intel G860)
Languages:All except: ASM64
Resource:My Own