we have to find the nth term of this series http://oeis.org/A028859
n<=1000000000
answer should be modulo 1000000007
i have written the code but time limit exceeds when n a is huge number.
#include<iostream>
using namespace std
int main()
{
long long int n;
cin>>n;
long long int a,b,c;
a=1;
b=3;
int i;
for(i=3;i<=n;i++)
{
c=(2ll*(a+b))%1000000007;
a=b;
b=c;
}
cout<<c;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With