I have an algorithm and I need help finding the complexity of it (tightest possible upper bound)
for(int i = 0; i < n/2; i++)
for(int j = 0; j < n/4; j++)
for(int k = 0; k < n; k++)
x++;
My analysis is that if n would not be divided in each for loop, it would be O(n^3)
. This complexity still holds true, since each "for loop" will reduce each operation to a O(log n)
complexity since it divides n every time the loop executes, making it smaller and smaller (smaller than O(n)
at least).
I would say that the answer is between O(log n)
and O(n^3)
. Could you help me getting the tightest possible bound?
start with inner loop :
for(int k = 0; k < n; k++)
x++;
is obviously O(n).
now one layer above that :
for(int j = 0; j < n/4; j++)
is O(n) because it takes n/4 for j to reach the n and we know that O(n/4) = O(n)
and like this for outer loop is O(n).so the complexity is O(n^3)
because you have three nested loop each with O(n) and non of them have effect on each other.