2

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?

Nikolay Kostov
  • 16,433
  • 23
  • 85
  • 123
idelara
  • 1,786
  • 4
  • 24
  • 48

3 Answers3

3

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.

Lrrr
  • 4,755
  • 5
  • 41
  • 63
3

Assume each step takes time C. For k-loop, time taken is Cn. For j-loop, time taken to complete iteration is (Cn)n/4=C(n^2)/4 For i-loop, time taken to complete iteration is (C*(n^2)/4)n/2=C(n^3)/8

So Total time taken=(C/8)*(n^3)

As C/8 is a constant it can be ignored when considering Big-O Notation. Thus, Time Complexity=O(n^3).

Lucifer
  • 41
  • 3
2
for(int i = 0; i < n/2; i++)    --> n/2
    for(int j = 0; j < n/4; j++)  --> n/4
        for(int k = 0; k < n; k++)  --> n
            x++;

Hence total complexity is O((n^3)/8) which is O(n^3)

pola sai ram
  • 832
  • 7
  • 23