What is the Big O analysis of this algorithm? (Stackoverflow ),
Question:
I'm working on a data structures course and I'm not sure how to proceed w/this Big O analysis:
sum = 0;for(i = 1; i < n; i++) for(j = 1; j < i*i; j++) if(j % i == 0) for(k = 0; k < j; k++) sum++;
My initial idea is that this is O (n ^ 3) after ction, because the innermost loop will only run whenj
/i
Has no remainder and the multiplication rule is inapplicable. Is my reasoning correct here?
Answer:
Let's ignore the outer loop for a second here, and let's analyze it in termsi
.
The mid loop runsi^2
Times, and is invoking the inner loop wheneverj%i == 0
, That means you run it oni, 2i, 3i, ...,i^2
, And at each time you run until the relevantj
, 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 priority ity comes from sum of arithmetic progression.
The above is inO(i^3)
.
Repeat this to the outer loop which runs from1
Ton
And you will get running timeO(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 inO(n^4)
, Which is your complexity.