nth term of series

若如初见. 提交于 2019-12-03 14:36:41

The standard technique for solving this type of problem is to rewrite it as a matrix multiplication and then use exponentiation by squaring to efficiently compute powers of the matrix.

In this case:

a(n+2) = 2 a(n+1) + 2 a(n)
a(n+1) = a(n+1)

(a(n+2)) = (2  2) * ( a(n+1) )
(a(n+1))   (1  0)   ( a(n)   )

So if we define the matrix A=[2,2 ; 1,0], then you can compute the n th term by

[1,0] * A^(n-2) * [3;1]

All of these operations can be done modulo 1000000007 so no big number library is required.

It requires O(log(n)) 2*2 matrix multiplications to compute A^N, so overall this method is O(log(n)), while your original method was O(n).

EDIT

Here is a good explanation and a C++ implementation of this method.

When long long is not enough, you probably want to use a bignum library. For example GNU MP.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!