1

My gut tells me the time-complexity of the following code is simply O(n^2). However, I'm not convinced, thinking it could possibly be O(n^3):

cin >> n;
sum = 0;
for (int i = 0; i < n; i++)
    for (int j = 0; j < n * n; j++)
        sum++;

Can anyone provide a distinction, and why?

Thanks in advance.

Raphael
  • 72,336
  • 29
  • 179
  • 389
user29291
  • 13
  • 2
  • See also [tag:runtime-analysis+loops]. And, important, here; $O(n^2)$ and $O(n^3)$ are not mutually exclusive, in fact $O(n^2) \subset O(n^3)$. You want to talk about $\Theta$. – Raphael Mar 02 '15 at 00:03

1 Answers1

2

Hint: What is the value of sum at the end of the code, as a function of $n$? If it is $s$ then the fifth line must have been run exactly $s$ times.

Yuval Filmus
  • 276,994
  • 27
  • 311
  • 503