0

There are two nested for loops. I'm not sure but I think that it's geometric series, but I cannot get well solution for it. It seems n + n/2 + n/4 + .. + n/n^2, but how? What I tried is below up to now,

$$ \sum _{i=0}^{log\left(n-1\right)}\:\sum _{j=0}^{i-1}\:1 $$ $$ \sum _{i=0}^n\:\sum _{j=0}^n\:\left(\frac{1}{2}\right)^j $$

At first, I thought it's $O(nlogn)$ but instead as far as I research the right result is $O(n)$.

int try(int n) {   
    int sum = 0;   
    for (int i = n; i > 0; i /= 2) {     
        for (int j = 0; j < i; j++) {      
          sum += 1; 
          }
    }  
    return sum;
} 

Could you show its sigma notation with its complexity? I want to comprehend it with steps.

  • 1
    I've voted to close this as a duplicate of one of our existing questions that I think you'll find helpful. However, I think you really need to talk to somebody face-to-face about this because I think you need more interactive help than our question and answer format can provide. The sums you've written don't have much relationship with the code you're trying to analyze, and you haven't stated any relationship between the two formulas. You've correctly identified that the outer loop assigns roughly $\log n$ different values to i, but what values are they? The code says $n$, $n/2$, ..., $1$ – David Richerby Oct 15 '17 at 10:55
  • ... but the maths says $1$, $2$, ..., $\log (n-1)$. So will that sum really model the behaviour of the code? As a first step, it might help to observe that the whole inner loop is just an inefficient way of writing sum += i. – David Richerby Oct 15 '17 at 10:56
  • Your sums are $\Theta(\log^2 n)$ and $\Theta(n)$, respectively. In fact, you can even compute them explicitly: the first one is $\log n \log(n-1)/2$, and the second one is $(n+1)(2-2^{-n})$. – Yuval Filmus Oct 15 '17 at 11:19
  • Yes, I'm aware of their results, but i wanted to show what i have tried so far sir. Would you mind telling the sigma notation for the code snippet? @YuvalFilmus – concurrencyboy Oct 15 '17 at 11:21
  • The correct result is indeed $\Theta(n)$. I think you should be able to come up with a formula on your own. Indeed, the running time is intimately related to the value of sum, which you can inspect by running your function on a few sample inputs. – Yuval Filmus Oct 15 '17 at 11:23

0 Answers0