edited by
1,145 views
2 2 votes

I think answer should be $O(n^{3})$

but given options are

$a.O(n^{4}) b.O(n^{5}) c.O(n^{6}) d.O(n^{7})$

What is the running time of the following code:

Consider following code fragment
(1) for i in $1 . . \mathrm{N}$ loop
(2) for j in $1 . . \mathrm{i}$ loop
(3) for k in 1 ...j loop
(4) sum: $=$ sum +1
(5) end loop:
(6) end loop;
(7) end loop:
(8) for p in $1 . . \mathrm{N}^{*} \mathrm{~N}$ loop
(9) for $q$ in I..p loop
(10) sum:=sum-1:
(11) end loop:
(12) end loop:

1 Answer

0 0 votes
For loop(Line no 1-7):

if n =1, i = 1, j = 1 time, k = 1 time
if n = 2, i = 2, j = 2 times, k = (1+2) times
if n = 3, i = 3, j = 3 times, k = (1+2+3) times
if n = n, i =n, j = n times, k = (1+2+3+-----+n) times

1+(1+2)+(1+2+3)+-----+(1+2+3+----+n)
so, time complexity = O(n^3)  

For loop(Line no. 8-12):
if n = 1, p = 1^2, q = 1^2
if n = 2, p = 2^2, q = 1+2+3+2^2
if n = 3, p = 3^2, q = 1+2+----+3^2
if n = n, p = n^2, q = 1+2+3+-----+n^2

So, time complexity  = O(n^4)

So, Time complexity of the program is = O(n^3+n^4) = O(n^4)
edited by
Answer:
Position:
Show:

Related questions

0 0 votes
1 1 answer
811
811 views
Beyonder asked Apr 11, 2018
811 views
2. What is asymptotical complexity of the following program: n= readInt()n = readInt()t = ms = 4for (int 1 = 0;105 += =m/= 2n=twriteInt(s) $O\left(n^{2} \times \log _...
2 2 votes
1 answers 1 answer
1.6k
1.6k views
gauravkc asked Apr 5, 2018
1,554 views
What is the time complexity of this code?What is the time complexity of the following code?for (int $\mathrm{i}=\mathbf{1} ; \mathrm{i}0 ; \mathrm{h}=\mathrm{h} / 2$ )sum...
3 3 votes
1 1 answer
1.4k
1.4k views
pranab ray asked Jan 15, 2018
1,413 views
Consider the following statements:\[\begin{array}{l}S_{1}: f(n)=\mathrm{O}\left((f(n))^{2}\right) \\S_{2}: \text { If } f(n)=\mathrm{O}(g(n)) \text { then } 2^{f(n)}=\mat...
0 0 votes
3 3 answers
789
789 views
pranab ray asked Jan 13, 2018
789 views
i am getting t.c as O(n^5) but given answer as O(n^4) what should be the answerWhat is the time complexity of the following code? void foo(int n) {int }s=0for (i=1;i\le...