1

Why is the time-complexity of

function (n)
{
    //this loop executes n times

    for( i = 1 ; i <= n ; i + + )
    //this loop executes j times with j increase by the rate of i
    for( j = 1 ; j <= n ; j+ = i )
    print( “*” ) ;

}

Its running time is n*(n^1/2)=n^3/2

so, O(n^3/2)

Please explain with mathematical steps.

Thank you in advance.

ovejka
  • 999
  • 1
  • 16
  • 21
Ankita
  • 37
  • 8

1 Answers1

1

The running time is bounded by O(n^{3/2}), but that's not tight!

Notice that the inner loop makes O(n/i) iterations for each i=1,2,...n), thus the time complexity is O(n * (1 + 1/2 + 1/3 + ... + 1/n)) = O(n log n).

This is because 1+1/2+1/3+...+1/n=O(log n) as it is the well-known harmonic series.

blazs
  • 4,705
  • 24
  • 38
  • For n=4....for i=1 ,inner loop executes 5 times (j=1 to 4) for n=4...for (i=2),it executes for j=1,3...2times and for (i=3), innerloop executes for j=1,4..again two times.. as j<=n ...So how does it make O(n/i) iterations? – Ankita Nov 09 '16 at 05:15
  • Because you are incrementing `j` by step `i`, you make at most `K` iterations, i.e., the number of iterations of the inner loop is the largest `K` for which `K * i < n`. This is bounded form above by `n/i`. That is, you make at most `ceil(n/i)` iterations in the inner loop when the outer lop is in `i`-th iteration. – blazs Nov 09 '16 at 07:30