What is the Big O analysis of this algorithm?

Let’s ignore the outer loop for a second here, and let’s analyze it in terms of i.

The mid loop runs i^2 times, and is invoking the inner loop whenever j%i == 0, that means you run it on i, 2i, 3i, ...,i^2, and at each time you run until the relevant j, this means that the inner loop summation of running time is:

i + 2i + 3i + ... + (i-1)*i  = i(1 + 2 + ... + i-1) = i* [i*(i-1)/2] 

The last equality comes from sum of arithmetic progression.

The above is in O(i^3).

repeat this to the outer loop which runs from 1 to n and you will get running time of O(n^4), since you actually have:

C*1^3 + C*2^3 + ... + C*(n-1)^3 = C*(1^3 + 2^3 + ... + (n-1)^3) = 
= C/4 * (n^4 - 2n^3 + n^2)

The last equation comes from sum of cubes

And the above is in O(n^4), which is your complexity.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)