To solve this problem, we need to compute the sum of the first N terms of the Fibonacci sequence modulo (10^9 + 7), especially for very large values of N (up to (10^{18})).
Approach
- Sum of Fibonacci Terms: The sum of the first N terms of the Fibonacci sequence can be derived using the identity:
(S(N) = Fib(N+2) - 1), where (Fib(k)) is the k-th Fibonacci number (with (Fib(0)=0, Fib(1)=1)). - Efficient Fibonacci Calculation: For large N, we use the Fast Doubling method, which computes Fibonacci numbers in (O(\log N)) time. This method leverages recursive divide-and-conquer and properties of Fibonacci numbers to handle very large values efficiently.
- Modulo Operation: Since the result can be large, all operations are performed modulo (10^9 +7) to keep numbers manageable and avoid overflow.
Solution Code
MOD = 10**9 + 7
def compute_fib(n):
def fast_doubling(n):
if n == 0:
return (0, 1)
a, b = fast_doubling(n // 2)
c = (a * ((2 * b - a) % MOD)) % MOD
d = (a * a + b * b) % MOD
if n % 2 == 1:
return (d, (c + d) % MOD)
else:
return (c, d)
return fast_doubling(n)[0]
n = int(input())
k = n + 2
fib_k = compute_fib(k)
sum_result = (fib_k - 1) % MOD
print(sum_result)
Explanation
- Fast Doubling: This method uses the following identities for Fibonacci numbers:
- (Fib(2n) = Fib(n) (2 Fib(n+1) - Fib(n)))
- (Fib(2n+1) = Fib(n)^2 + Fib(n+1)^2)
These identities allow us to split the problem into smaller subproblems, reducing the time complexity to (O(\log N)).
- Sum Calculation: Using the identity (S(N) = Fib(N+2) -1), we compute (Fib(N+2)) and subtract 1, then take modulo (10^9+7) to get the final result.
This approach efficiently handles very large values of N, making it suitable for the given constraints. The Fast Doubling method ensures that even for (N=10^{18}), the computation is done in around 60 steps (since (\log_2(10^{18}) \approx 60)).
Example: For N=5, the sum of the first 5 terms (0+1+1+2+3+5) is 12. Using the identity: (Fib(5+2)=Fib(7)=13), so (13-1=12), which is correct.
This solution is optimal and handles all edge cases (like N=0, which returns 0). It is designed to be both time and space efficient.


(免责声明:本文为本网站出于传播商业信息之目的进行转载发布,不代表本网站的观点及立场。本文所涉文、图、音视频等资料的一切权利和法律责任归材料提供方所有和承担。本网站对此资讯文字、图片等所有信息的真实性不作任何保证或承诺,亦不构成任何购买、投资等建议,据此操作者风险自担。) 本文为转载内容,授权事宜请联系原著作权人,如有侵权,请联系本网进行删除。