edited by
458 views
0 votes
0 votes

Complexity of the following snippet is 

for (i=1;i<n;++i)
    for(j=1;j<=n;j=j+i)
        c=c+1;
edited by

2 Answers

Best answer
3 votes
3 votes

See we analyse this as :

When i = 1 , j is incremented in steps of 1 as j = j + i and i = 1 for 1st iteration..

So j as clear from the program runs from 1 to n and increment is done by 1 in each inner loop..

So number of times the inner loop runs = n for i = 1

Similarly for i = 2 , inner loop runs n/2 times as j = j + 2 for i = 2..

Similarly for i = 3 , inner loop runs n/3 times as j = j + 3 for i = 3..

and so on till i = n-1

So time complexity = n + n/2 + n/3 + n/4...................

                             = n(1 + 1/2 + 1/3 ..........)

Now the series written inside the brackets is a harmonic series ..So addition formula is not there..However we can approximate by doing the integration of 1/n w.r.t n which gives us logn..

So time complexity  = O(nlogn)

selected by
2 votes
2 votes
for a general i-th iteration, the inner loop runs O(n/i)

O(n + n/1 + n/2 + ..... + n/n) = O((n)(1 + 1 + 1/2 + .... +1/n)) = O(nlogn)

Related questions

3 votes
3 votes
1 answer
1
PEKKA asked Jan 2, 2017
569 views
f(n) = $\Theta (n^{2})$ g(n) = $\Omega (n)$ h(n)=O(log n) then [ f(n) . g(n) ] + [h(n) . f(n) ] is $\Omega (n)$$\Theta (n^{2})$O(log n)None
1 votes
1 votes
1 answer
2
PEKKA asked Dec 6, 2016
433 views
Complexity of the below code snippet is ..for (i=1;i<=n;++i) { j=2; while(j<=n) { j=j*j; c=c+1; } }$O(nlog n)$$O(n^{2})$$O(nloglog n)$$O(n)$
0 votes
0 votes
1 answer
4
PEKKA asked Dec 5, 2016
337 views
L={ambnckdl | (n-k ) is odd only if (m-l) is odd , m,n,k,l >=0 } is best fit under which language classRLDCFLCFLCSL