• edited by
856 views
2 2 votes

Consider the following program segment?
```
main ()
\{
int $i=0$; int $c=0$;
For $(i=1 ; i \leq n ;++i)\{$
For $\left(j=1 ; j \leq i^{*} i ;++j\right)\{$
If $((j \% i)==0)$
For $(k=1 ; k \leq j,++k)\{$
$c=c+1$
\}
\}
\}
\}
```

Which of the following will represent time complexity of above program segment?

  1. $\mathrm{O}\left(n^{3}\right)$
  2. $O\left(n^{4}\right)$
  3. $O\left(n^{2}\right)$
  4. $O\left(n^{5}\right)$

2 Answers

Best answer
3 3 votes

$\large\color{red}{O(n^4)}$

• selected by
3 3 votes

j is depend upon i and k is depend upon i and j ===> we have to unroll the dependency

when i=1

j=1 ===> k=1

 

when i=2

j=1 ===> k didn't run

j=2 ===> k run 2 times

j=3 ===> k didn't run

j=4 ===> k run 4 times

∴ 2+4 == 2(1+2)

 

when i=3

j=1 ===> k didn't run

j=2 ===> k didn't run

j=3 ===> k run 3 times

j=4 ===> k didn't run

j=5 ===> k didn't run

j=6 ===> k run 6 times

j=7 ===> k didn't run

j=8 ===> k didn't run

j=9 ===> k run 9 times

∴ 3+6+9 == 3(1+2+3)

.......

when i=p

j=1 ===> k didn't run

j=2 ===> k didn't run ......

j=p ===> k run p times 

j=p+1 ===> k didn't run

j=p+2 ===> k didn't run .............

j=2p ===> k run 2p times

j=2p+1 ===> k didn't run

j=3p ===> k run 3p times ..............

j=p*p ===> k run p*p times

∴ p+2p+3p+......+p2 == p(1+2+3+....+p)

 

Total = 1 ( 1 ) + 2 . ( 1+2 ) + 3. ( 1+2+3 ) + ......+ p . ( 1+2+3+....+p ) +....... + n . ( 1+2+....+n )

from these observations we can conclude that

Time complexity = $\LARGE \sum_{i=1}^{n} ( i$$\sum_{j=1}^{i} j \LARGE) $

                          = $\LARGE \sum_{i=1}^{n} ( i$ ( 1+2+3+...i )$ \LARGE) $

                          = $\LARGE \sum_{i=1}^{n} ( i$ $( \frac{i(i+1)}{2} $ $ \LARGE) $

                          = $\frac{1}{2}\LARGE \sum_{i=1}^{n} ( i^{3} + i^{2} $ $ \LARGE) $

                          = O(n4)

note that summation of first n natural cubes =$ {( \frac{n(n+1)}{2}) }^{2}$

Answer:
Position:
Show:

Related questions

0 0 votes
1 1 answer
1.1k
1.1k views
Anuj1995 asked Jan 10, 2019
1,120 views
What is the right answer?Insertion sort: takes $10 \mathrm{n}^{2}$ to sort n times. Merge sort: take 100 nlogn to sort n times. Consider a faster computer A running inser...
2 2 votes
1 1 answer
1.7k
1.7k views
thepeeyoosh asked Jan 11, 2018
1,735 views
Consider the multi selection problem:Given a set ' S ' of n elements and set ' K ' of ' r ' ranks $\mathrm{K}_{1}, \mathrm{~K}_{2}, \mathrm{~K}_{3}$, $\qquad$ $\mathrm{K}...
1 1 vote
1 1 answer
841
841 views
nikkey123 asked Jan 3, 2018
841 views
Determine the aspmptotic running time of $f(n)$.int f(int n)\{int $x$;if $(\mathrm{n}==0) x=1$;else $x=f(\mathrm{n}-1)^{*} 2$;$\mathrm{g}(x)$;return $x$;\}void g(int m)[i...
1 1 vote
1 1 answer
1.8k
1.8k views
Kaluti asked Dec 6, 2017
1,812 views
Consider Bottom-up mergesort working on ' $n$ ' elements. Assume ' $n$ ' is a power of 2 . The minimum number of comparisons in order to get sorted list is$\frac{n \log n...