0
$\begingroup$

What will be the time complexity of the following function? is it $O(n^3)$ or $O(n^4)$?

i am getting $O(n^3)$ in the first for loop, it will undergo $n$ times. in the second for loop, for every nth element it will go $n^2$ times, therefore the total complexity till here is $O(n^3)$ now, the if statement will only hold true value only for n out of $n^2$ values, and for every $n$ values the $k$- for loop will go till $n^2$ elements and hence the complexity is $O(n^3)$. I have taken few values of $n$: for $n=3$ ,$c=25$

for $n=10$, $c=1705$

for $n=50$, $c=834275$

for(i=1;i<=n;++i)                            
    for(j=1;j<=(i*i);++j)  
        if((j%i)==0)                               
            for(k=1;k<=j;++k)      
                c=c+1;

1 Answers 1

1

The innermost loop executes its body $j$ times.

The middle loop executes the innermost loop for every multiple of $i$ in $[1,i^2]$, i.e. for $j=i,2i,3i,\cdots i^2$. Hence the total workload is proportional to $i\dfrac{i(i+1)}2$.

The outermost loop executes its body $n$ times, for increasing $i$, hence

$$\frac12\sum_{i=1}^ni^2(i+1)=\frac12\left(\frac{n^4+2n^3+n^2}4+\frac{2n^3+3n^2+n}6\right)=\frac{3n^4+10n^3+5n^2+2n}{24}.$$


For a gross estimate, you can write

  • inner, $O(j)$;

  • intermediate, $i$ times sum of $O(j)$, $O(i\cdot i^2)=O(i^3)$;

  • outer, sum of $O(i^3)$, $O(n^4)$.