The Gateway to Computer Science Excellence
First time here? Checkout the FAQ!
x
+1 vote
121 views
for(i=1;i<=n;i++)
    for(j=1;j<=i;j++)
        for(k=1;k<=j;k++)
            for(l=1;l<=k;l++)
                printf("gate");

 

asked in Algorithms by (25 points) | 121 views

2 Answers

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

Answer is O(n^4)
answered by Veteran (32k points)

I think its O(n2)

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$
answered by Veteran (327k points)

Related questions

+2 votes
3 answers
1
asked in Algorithms by admin Loyal (2.5k points) | 350 views
0 votes
1 answer
2
+1 vote
0 answers
3


Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true

29,157 questions
36,985 answers
92,166 comments
34,824 users