1

I have code like this:

for (int i = 0; i <= n; i++)
{
    for (int j = 0; j <= i; j++)
    {
        f(); // constant operation
    }
}

The number of times f would execute appear to be:

n+n+(n-1)+(n-2)+(n-3)+...+2+1+0 = (n*n)-n = n^2-n

If we drop the low-order term (-n), The big O would be O(n^2).

Is this all correct?

Matt Timmermans
  • 53,709
  • 3
  • 46
  • 87
lightning_missile
  • 2,821
  • 5
  • 30
  • 58

1 Answers1

0

Your derived complexity is correct, but there are two errors in your equation for the number of times the loops run for:

for (int i = 0; i <= n; i++)
{
    for (int j = 0; j <= i; j++)
    {
        f(); // constant operation
    }
}

There are n + 1 distinct values in the inclusive range 0 to n, so your inner loop will run for i + 1 iterations. As such, your formula should be:

(n + 1) + n + (n - 1) + ... + 1 + 0 = n(n + 1)/2 = (n^2 + n)/2

As it's an arithmetic series. This is still O(n^2), as n^2 grows faster than n and the constant 1/2 doesn't matter.

hnefatl
  • 5,860
  • 2
  • 27
  • 49