Search code examples
algorithmrecursionanalysisrecurrence

Solving a recurrence relation for a recursive function


enter image description hereI need to create and solve a recurrence relation for the worst-case analysis for the following psuedocode. I am counting the number additions (not including the for loop counter) as my basic operation. I am assuming n=2^k.

Here is the progress I have made... Base Case: T(n<=4) = 1

W(n)=W(2^k)=additions to calculate answer+additions in next recursion+addition in for loop W(2^k) = 2 + W(2^(k-2)) + (2^k) - 2 = W(2^(k-2)) + (2^k)

I use back substitution and get the following recurrence relation...

for the jth recursive call W(2^k) = W(2^(k-2j)) + (2^k) + sum(t=1,j,2^(k-2(t-1)))

I know that I can simplify this because I take W(2^(k-2j)) = W(4) and solve for j to see how many recursive steps the code takes. In this case, j=(k/2) - 1. Reducing the recurrence gives me...

W(2^k) = 1 + (2^k) + sum(t=1,j,2^(k-2(t-1))).

Reducing the summation gives me...

W(2^k) = 1 + (2^k) + (2^k)*(2^2)*sum(t=1,j,2^(-2t)) or

W(n) = 1 + n + 4n*sum(t=1,j,2^(-2t))

What I cannot simplify is the summation. In lectures, we may have a summation of sum(i=1,n,2^i), which would be 2^(n+1)-1, but this one is different.

int function calc(int n) {
   int num,answer;
   if(n<=4) {return n+10;}
   else {
     num=calc(n/4);
     answer=(num+num+10);
     for(int i=2;i<=n-1;i++) {
         answer=answer+answer;
     }
     return answer;
  }
}

Any help would be appreciated. This assignment is due tonight. Thanks


Solution

    • T(n) = T(2^k) // by assumption
    • T(n) = T(n/4) + n // is the recurrence relation
    • T(2^k) = T(2^(k-2)) + (2^k) // rewriting
    • T(2^k) = T(2^(k-2j)) + (2^k)*SUM(i=0;j-1;(1/4)^i) // is the relation for iteration j
    • T(4) = T(2^(k-2j)) = 1 // when the recursion ends, base case reached, only 1 addition
    • 2^2 = 2^(k-2j) // rewrite and remove T
    • 2=k-2j // remove common base
    • j=(k/2)-1 // solve for jth iteration
    • Notice: cannot have decimal for iteration, so j=CEILING((k/2)-1)
    • SUM(i=0;j-1;(1/4)^i) = (1-(1/4)^j)/(1-(1/4))
    • For geometric sums and proof of transformation above, see wiki link below
    • Substituting j with CEILING((k/2)-1), the summation is...
    • SUM = (1-(1/4)^(CEILING((k/2)-1)))/(1-(1/4))
    • Finally, T(2^k) = 1 + (2^k)*SUM
    • In terms of the input n, T(n) = 1 + (n*SUM)
    • This formula is good for all k>=1

    Testing several values...

    • k=1, T(2) = 1 + (2*0) = 1 // we know this is true because T(2) is a base case
    • k=2, T(4) = 1 + (4*0) = 1 // we know this is true because T(4) is a base case
    • k=3, T(8) = 1 + (8*1) = 9 // by recurrence formula, T(8) = T(2) + 8 = 9, true
    • k=4, T(16) = 1 + (16*1) = 17 // by recurrence formula, T(16) = T(4) + 16 = 17, true
    • k=5, T(32) = 1 + (32*1.25) = 41 // by recurrence formula, T(32) = T(8) + 32, T(8) = 9, 32+9=41 true

    For geometric sums https://en.wikipedia.org/wiki/Geometric_series