Time-complexity of nested for loop

algorithmsbig o

I have loops like this:

for(int i = 0; i < n; i++) {
    for(int j = 0; j < i; j++) {
        sum += 1;
    }
}

It's O(n * ), but I'm not sure what the j < i loop is.

I have some tests that I ran,

n = 10, runs = 45

n = 20, runs = 190

n = 40, runs = 780

n = 80, runs = 3160

n = 10, runs = 12720

It seems to be converging onto .5*n^2, but I'm not quite sure.

Best Answer

You are summing up the numbers from 1 to n, incrementing the value by one each time. This is essentially the classic Gauss sumation which is:

sum(1 .. n) = (n * n-1)/2

This also happens to be the number of times through the loop.

(n^2 - n) / 2
(n^2)/2 - n/2

When representing Big O, only term with the highest power is used and constants are thrown away, and thus the answer is O(n2).

More about this particular problem can be read on CS.SE at Big O: Nested For Loop With Dependence