The Gateway to Computer Science Excellence

First time here? Checkout the FAQ!

x

+1 vote

+1 vote

Time complexity of nested loops is equal to the number of times the innermost statement is executed.

Answer is O(n^4)

Answer is O(n^4)

0 votes

$T(n) = \sum_{i=1}^{n} \sum_{j=1}^{i} \sum_{k=1}^{j} \sum_{l=1}^{k} c$

( Taking cost of printf as $c$)

$= c\sum_{i=1}^{n} \sum_{j=1}^{i} \sum_{k=1}^{j} k $

$= c\sum_{i=1}^{n} \sum_{j=1}^{i} \frac{j.(j+1)}{2} $

$= d \sum_{i=1}^{n} \sum_{j=1}^{i} (j^2 + j)$

$(d = c/2)$

$= d \sum_{i=1}^{n} \frac{i.(i+1)(2i+1)}{6} + \frac{i.(i+1)}{2})$

$= e \sum_{i=1}^{n} 2i^3 + 3i^2 + i + 3i^2 + 3i $

$(e = d/6)$

$= e \sum_{i=1}^{n} 2i^3 + 6i^2 + 4i $

Well, sum of the cubes of first $n$ natural numbers is $\left({\frac{n.(n+1)}{2}}\right)^2 = \Theta\left (n^4\right)$

So, our answer will also be $\Theta\left( n^4\right)$ due to the $i^3$ term going from $i=1..n$

( Taking cost of printf as $c$)

$= c\sum_{i=1}^{n} \sum_{j=1}^{i} \sum_{k=1}^{j} k $

$= c\sum_{i=1}^{n} \sum_{j=1}^{i} \frac{j.(j+1)}{2} $

$= d \sum_{i=1}^{n} \sum_{j=1}^{i} (j^2 + j)$

$(d = c/2)$

$= d \sum_{i=1}^{n} \frac{i.(i+1)(2i+1)}{6} + \frac{i.(i+1)}{2})$

$= e \sum_{i=1}^{n} 2i^3 + 3i^2 + i + 3i^2 + 3i $

$(e = d/6)$

$= e \sum_{i=1}^{n} 2i^3 + 6i^2 + 4i $

Well, sum of the cubes of first $n$ natural numbers is $\left({\frac{n.(n+1)}{2}}\right)^2 = \Theta\left (n^4\right)$

So, our answer will also be $\Theta\left( n^4\right)$ due to the $i^3$ term going from $i=1..n$

- All categories
- General Aptitude 1.1k
- Engineering Mathematics 4k
- Digital Logic 1.7k
- Programming & DS 3k
- Algorithms 2.6k
- Theory of Computation 3.2k
- Compiler Design 1.2k
- Databases 2.4k
- CO & Architecture 2.1k
- Computer Networks 2.4k
- Non GATE 819
- Others 1.1k
- Admissions 244
- Exam Queries 420
- Tier 1 Placement Questions 16
- Job Queries 39
- Projects 4

29,157 questions

36,985 answers

92,166 comments

34,824 users