0

The first loop would give O(n) but the second loop will run forever won't it? Would this mean the overall O(n) is just O(n) or does the inner for loop count as something more than a constant?

for (int i=0; i<n; i++) {
  for (int j=0; j<=42; j--) {
    System.out.println(i+j);
  }
}
Askav
  • 1
  • 2
  • 2
    I suspect the O notation does not apply here since the program does not implement an algorithm as an algorithm must be a finite set of steps. – Aleksander Bobiński Jun 12 '21 at 10:37
  • We cannot suppose the inner loop to be a constant although it seems so (since everything is a number there) and hence the complexity of this code is undefined – potter1024 Jun 12 '21 at 11:18

1 Answers1

1

The System.out.println indicates this is Java.

In Java, the int type is a 32-bit signed integer type, with values ranging from -2,147,483,648 to 2,147,483,647. Decreasing a variable that is already at the minimum value wraps it around to the maximum.

This means that the inner loop will run for 2,147,483,648 iterations before the variable j wraps around, becomes larger than 42, and terminates the inner loop. The inner loop is thus not infinite, as indicated in the question, but instead finite and constant.

Since the inner loop always execute this many steps, it is constant, and thus the big-o notation is wholely dictated by the outer loop.

So the big-o notation for this piece of code is O(n).

If the compiler/runtime can be configured to crash when you try to underflow an int, instead of wrapping it, the program will always crash, and it will manage to just run 1 iteration of the outer loop before it crashes at the end of the inner loop. It would thus be O(1). I do not know enough Java, however, so I don't know if this is possible.

If instead of Java, this is supposed by be in context of another theoretical programming language, or seen upon as a pure algorithmic description, in which int does not actually have a lower bound, then the program does not terminate and it does in fact not have a big-o notation at all.

More about this last paragraph here: O-notation, O(∞) = O(1)?.

Lasse V. Karlsen
  • 380,855
  • 102
  • 628
  • 825