-2

Possible Duplicate:
I want to generate the nth term of the sequence 1,3,8,22,60 ,164 in Order(1) or order of (nlogn)

What I do now is:

t1 = 1, t2 = 0,MOD = 1000000007;

for i = 1:n 

    t1_new = (2*(t1+t2)) % MOD;
    t2_new = t1;
    a[i] = (t1_new + t2_new) % MOD;   // where a[i] is the ith term mod p
    t1 = t1_new;
    t2 = t2_new;

return a[n]; // the required ans

But it is an O(n) solution.

Please give me only hints(no solution please) so that I can reduce the complexity of the solution.

Community
  • 1
  • 1
TheRock
  • 323
  • 7
  • 14
  • 1
    Here's a hint: don't store the old results in an array so that `a` can become a register variable. – Fred Foo Jul 03 '12 at 10:07
  • 6
    What is the recurrent relation between t_n and t_(n-1) ? t_n = 2 * (t_(n-1) + t_(n-2)) ? Try to solve this recurrence equation using the characteristic equation. – Viktor Latypov Jul 03 '12 at 10:07

2 Answers2

3

You can use the folowing fact. If you consider the matrix

    (0 1)
A = (2 2)

You can use the fact that an = An-2 * (1, 3)[1] (here (1,3) is a vector) and [1] means second coordinate of the vector. Here you can use binary exponentiation for the matrix. Consider the cases for n<=2 separately.

Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176
  • Thanks! Using this I hope to get a complexity of O(log n). – TheRock Jul 03 '12 at 10:57
  • Could you please explain how you came to this solution. Is this any standard sequence? – TheRock Jul 05 '12 at 11:27
  • @TheRock: You can use this for any sequence that is a linear combination of previous terms. Calculate (t_{n-1}, t_n) to try and see how this works. – JPvdMerwe Jul 05 '12 at 13:07
  • @TheRock: Check out the problem "Tiling Mall" in [http://olympiad.cs.uct.ac.za/old/may_2009/may_2009.pdf](http://olympiad.cs.uct.ac.za/old/may_2009/may_2009.pdf) along with the write up for the solution in [http://olympiad.cs.uct.ac.za/old/may_2009/may_2009_solutions.pdf](http://olympiad.cs.uct.ac.za/old/may_2009/may_2009_solutions.pdf). For a more complicated example of this technique. – JPvdMerwe Jul 05 '12 at 13:16
-1

you don't need an array at all to achieve this.

int n = 5;
int result = 0;

for (int i=0; i<n; ++i)
{
    int t1_new = (2*(t1+t2)) % MOD;
    int t2_new = t1;

    result = (t1_new + t2_new) % MOD;
    t1 = t1_new;
    t2 = t2_new;
}

int res = result;

that way, you will get the nth term, and not all of them across the way until n.

Mare Infinitus
  • 8,024
  • 8
  • 64
  • 113