retagged by
5,020 views
4 votes
4 votes
sum = 0;
for( i = 0; i < n; i++)

for( j = 0; j < i*i; j++)

 

for( k = 0; k < j; k++)

 

sum++;

 

how to solve this  :( help someone    time complexity = o(n^5 )  how ??
retagged by

3 Answers

Best answer
4 votes
4 votes

try to find out for each i, how many times innermost for-loop loops through

for i=0, j will go from 0-0, and k = 0 times

for i=1, j will go from 0, 1 and for each j i'e  j=0, k= 0 times, for j=1, k= 1 times . so total ( 0 + 1) times

similarly for i = 2 check the below image --

 

selected by
3 votes
3 votes

The running time for the operation sum++ is a constant. 
The most inner loop runs at most n^2 times, the middle loop also runs at most n^2 times, and the outer loop runs n times, thus the overall complexity would be O(n5).

2 votes
2 votes

think this way

1)sum = 0;
for( i = 0; i < n; i++)

sum++

this executes  n times look like

        n-1
        ---            
        \                      
        /   1  =   n-1   So T(n) = O(n)
        ---            
        i=1 

this executes  n times

2)sum = 0;
for( i = 0; i < n; i++)

for( j = 0; j < i*i; j++)

sum++

        n-1    i^2-1        n-1
        ---   ---          ---
        \     \            \      
        /     /    1  =    /    i^2-1  =    So T(n) = O(n^3)
        ---   ---          ---
        i=0   j=0          i=0

let consider loop imitial condition start from 1

3) sum = 0;
for( i = 1; i <= n; i++)

for( j = 1; j <= i*i; j++)

 for( k = 1; k <= j; k++)
 
sum++;

      n     i^2         j                  n      i^2                   n  
        ---   ---         ---               ---     ---                    ---
        \     \           \                  \        \                    \ 
        /     /           /    1    =      /         /    j  =        /   i2(i2+1)/2            
        ---   ---         ---               ---        ---                 ---
        i=1   j=1      k=1         i=1       j=1                   i=1

      

 

then 

         n
        ---            
        \                      
        /   (i4+i2)/2 =   
        ---            
        i=1 

Sigma n^4 = n*(n+1)*(2*n+1)*(3*n2+3*n-1)/30 =O(n5)

Sigma (n^2) = n(n+1)(2n+1)/6 =O(n3)

so overall O(n5)

edited by

Related questions

0 votes
0 votes
0 answers
3
0 votes
0 votes
0 answers
4
Sajal Mallick asked Nov 27, 2023
192 views
As we have to select maximal set of “non overlapping” activities. So like job scheduling algo of greedy we can solve it. So according to that complexity must be O(n l...