retagged by
835 views
3 votes
3 votes
Find the time complexity of the following snippets

1.

for$\left ( i=1;i\leqslant n;i++ \right )$

      for$\left ( j=n/3;j\leqslant 2n;j=j+n/3 \right )$

                 $x=x+1;$

2.

for$\left ( i=1;i\leqslant n;i++ \right )$

      for$\left ( j=1;j\leqslant n;j=j+i \right )$

                 $x=x+1;$
retagged by

3 Answers

Best answer
4 votes
4 votes

7.

for$\left ( i=1;i\leqslant n;i++ \right )$

      for$\left ( j=n/3;j\leqslant 2n;j=j+n/3 \right )$

                 $x=x+1;$

Time Complexity will be number of times   $x=x+1;$ will execute.

Inner Loop will execute exactly 6 times

$n/3\rightarrow 2n/3\rightarrow n\rightarrow 4n/3\rightarrow 5n/3\rightarrow 2n$ whatever the value of "n" is  and is Independent of outer loop

Thus time complexity will  number of times outer loop execute $\Rightarrow \Theta \left ( n \right )$

8.

for$\left ( i=1;i\leqslant n;i++ \right )$

      for$\left ( j=1;j\leqslant n;j=j+i \right )$

                 $x=x+1;$

time complexity = number of times "x=x+1" will execute .given below is the table$\Rightarrow$

  i   j
  1 n
  2 n/2
  3 n/3
  4 n/4
$\cdots$ $\cdots$
n n/n

time complexity $T\left ( n \right )=n+n/2+n/3+n/4+\cdots n/n$

$\Rightarrow T\left ( n \right )=n\left ( 1+1/2+2/3+n/4+\cdots 1/n \right )$

We know $\left ( 1+1/2+2/3+n/4+\cdots 1/n \right )\approx \log n$

$\Rightarrow T\left ( n \right )=\Theta \left ( n*logn \right )$

selected by
5 votes
5 votes
A. O(n)

Bcz inner loop always run for 6 times.

Bcz we start j=n/3 and every time increasing j by n/3  and want to reach upto 2n  i.e. 6(n/3)= 2n

So O(6n)=O(n)

B. O(nlogn)

Bcz our statement x=x+1 runs here

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

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

n(Harmonic Progression)

n(logn)

=O(nlogn)
edited by

Related questions

2 votes
2 votes
2 answers
1
Kapil asked Jul 8, 2016
1,402 views
The equality of two regular expression is computed in? Give reasons also..Constant Timepolynomial timelogarithmic Polynomial timeExponential time
0 votes
0 votes
1 answer
2
iarnav asked Jun 12, 2018
878 views
Given an sorted array in descending order, what will be the time complexity to delete the minimum element from this array?
1 votes
1 votes
2 answers
3
vishal chugh asked Jan 24, 2018
1,785 views
What is the worst case time complexity to find kth smallest element into an array of ‘n’ element?
0 votes
0 votes
1 answer
4
LavTheRawkstar asked Jan 12, 2017
838 views
INSERTION-SORT (A, n) ⊳ A[1 . . n]for (j ← 2 to len(A) ){key ← A[ j];i ← j – 1 ; while (i 0 and A[i] key) { A[...