Hi. I am trying to solve the following recurrence relation that was gotten from the following code.
void rotateR(int n)
{
if (n>1)
{
rotateR(n-1);
int t = A[0];
A[0] = A[n-1];
A[n-1] = t;
}
}
I got the following: T(n) = T(n-1) + 4
I then went about to try to solve it
T(n) = T(n-1) + 4, T(1) = 1
T(n-1) = T(n-2) +4 + 4
T(n-1) = T(n-2) + 2(4)
T(n-2) = T(n-3) + 2(4) + 4
T(n-2) = T(n-3) + 3(4)
T(n) = T(n-k) + k(4)
= T(n-n) +n(4)
= T(0) + 4n
= 4n
but I should be getting T(n) = 4n - 3
can anyone tell me where I went wrong? I know there are quite a few areas where I could have gone wrong, even when getting the original recurrence relation. Thanks in advance
void rotateR(int n)
{
if (n>1)
{
rotateR(n-1);
int t = A[0];
A[0] = A[n-1];
A[n-1] = t;
}
}
I got the following: T(n) = T(n-1) + 4
I then went about to try to solve it
T(n) = T(n-1) + 4, T(1) = 1
T(n-1) = T(n-2) +4 + 4
T(n-1) = T(n-2) + 2(4)
T(n-2) = T(n-3) + 2(4) + 4
T(n-2) = T(n-3) + 3(4)
T(n) = T(n-k) + k(4)
= T(n-n) +n(4)
= T(0) + 4n
= 4n
but I should be getting T(n) = 4n - 3
can anyone tell me where I went wrong? I know there are quite a few areas where I could have gone wrong, even when getting the original recurrence relation. Thanks in advance
-
T(n) = T(n-1) + 4
T(n-1) = T(n-2) + 4
...
T(2) = T(1) + 4
Add all above together,
T(n) = T(1) + 4*(n-1)
= 1 + 4(n-1)
= 4n - 3
----------------------------------
In your work,
T(n-1) = T(n-2) + 2(4)
T(n-2) = T(n-3) + 3(4)
etc are wrong. They should read
T(n-1) = T(n-2) + 4 and
T(n-2) = T(n-3) + 3.
The line
T(n) = T(n-k) + k(4)
is correct. You can use this to get the answer [by letting k=n-1]:
T(n) = T(n-(n-1)) + (n-1)*4 = T(1) + (n-1)4 = 4n-3.
T(n-1) = T(n-2) + 4
...
T(2) = T(1) + 4
Add all above together,
T(n) = T(1) + 4*(n-1)
= 1 + 4(n-1)
= 4n - 3
----------------------------------
In your work,
T(n-1) = T(n-2) + 2(4)
T(n-2) = T(n-3) + 3(4)
etc are wrong. They should read
T(n-1) = T(n-2) + 4 and
T(n-2) = T(n-3) + 3.
The line
T(n) = T(n-k) + k(4)
is correct. You can use this to get the answer [by letting k=n-1]:
T(n) = T(n-(n-1)) + (n-1)*4 = T(1) + (n-1)4 = 4n-3.