Search code examples
time-complexitybig-onested-for-loop

Time Complexity of multiple nested loops


What would be the complexity of the below code : Since the increment is not by 1 and the conditions are not direct, how to calculate the complexity ?

for(int h =0; h<n;h+=2)
    {
       for (int j =1; j<=n*n; j*=3)
       {
          for (int k =2; k+k <=n;++k)
          { 
          } 
       } 
    }

Solution

  • There are 3 nested loops. Let's analyze each of them (keep in mind that we don't care about any constants, no matter how large they are):

    for(int h=0; h<n; h+=2) - O(12N) -> O(N)

    for (int j=1; j<=n*n; j*=3) - O(log3N2) -> O(logN2)

    for (int k=2; k+k<=n; ++k)- O(12N) -> O(N)

    Since all the loops are nested O(N * logN2 * N) -> O(N2*logN2)