0

I can't able to find the theta for some type of code like.

for(i=1;i<=n;i++){
 for(j=i;j>=1;j=j/3){
 ....
 }
}

How to find the theta for the above code.

It will be really helpful if some one help me how to find it in general case like.

for(i=1;i<=n;i++){
 for(j=i;j>=1;j=j/K){
 ....
 }
}

Ps: I know it for k=2 which is n*logn

Thanks in Advance

1 Answers1

1

Start from the inner loop out.
Each iteration of the inner loop takes Theta(log_K(i)) iterations, since the iterator j starts from i and decays exponentially.

So, you have to combine that with the outer loop now, which is a simple incremental loop.
Thus, the outer loop takes:

Theta(log_K(1) + log_K(2) + log_K(3) + ... + log_K(n)) = 
= Theta(log_K(1*2*...*n)) = Theta(log_K(n!)) = 
= Theta(n*log_K(n)) = Theta(nlogn)

The last equality is because log_K(x) = log_2(x) / log_2(K), but log_2(K) is a constant.


I am assuming you mean for(j=i;j>=1;j=j/3){, and NOT for(i=j;j>=1;j=j/3){ (i and j switched on initialization)

amit
  • 175,853
  • 27
  • 231
  • 333
  • Thank you so much this is really helpful. But, I am confused with log_K(i), can you please provide me the explanation for getting log_K(i) for the inner loop. Thanks in Advance – Krishna Chikkala Sep 09 '14 at 17:20
  • Hi Amit Can you please give me the explanation for Theta(log_K(i)) (inner loop) – Krishna Chikkala Sep 10 '14 at 06:54
  • @user2553748 By dividing by `k` each iteration, you make the variable `j` decay exponentially in `k`. (it is first `j`, then `j/k`, then `j/k^2`, then `j/k^3`, ...). exponential decay mean it is O(log(i)) – amit Sep 10 '14 at 06:57