The standard method for solving this type of problem is to rewrite it as matrix multiplication, and then use exponentiation by squaring to efficiently calculate the 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 calculate the nth term on
[1,0] * A^(n-2) * [3;1]
All these operations can be performed modulo 1000000007, so a library of large numbers is not required.
Computing A ^ N requires O (log (n)) 2 * 2 matrix multiplications, so this whole method is O (log (n)), and your original method is O (n).
EDIT
Here is a good explanation and implementation of this method in C ++.
source share