I want to generate the nth term of the sequence 1,3,8,22,60 ,164 in Order(1) or order of (nlogn)
You can calculate values of sequences with a linear recurrence relation in O(log n) steps using the matrix method. In this case, the recurrence matrix is
2 2
1 0
The n
-th term of the sequence is then obtained by multiplying the n
-th power of that matrix with the two initial values.
The recurrence immediately translates to
|x_n | |2 2| |x_(n-1)|
|x_(n-1)| = |1 0| * |x_(n-2)|
thus
|x_(n+1)| |2 2|^n |x_1|
|x_n | = |1 0| * |x_0|.
In this case the initial conditions give, x_1 = 1, x_2 = 3
lead to x_0 = 0.5
, a non-integer value, hence the calculation should rather be
|x_(n+1)| |2 2|^(n-1) |x_2|
|x_n | = |1 0| * |x_1|.
To get the value modulo some number, calculate the power of the matrix modulo that number.