0

I currently have the following pseudo code, and I am trying to figure out why the answer to the question is O(n).

sum = 0;
for (i = 0; i < n; i++) do
    for (j = n/3;j < 2*n; j+= n/3) do
        sum++;

I thought the answer would be O(n^2) since the first for loop would run 'n' times and the second for loop has += n/3, giving it another (n divided by something times), which would just simplify to O(n^2). Could somebody explain why it is O(n)?

2 Answers2

1

This is because the second loop runs in constant amount of operations (does not depend on n). From n/3 to 2n with a step n/3 which is similar to from 1/3 to 2 with a step 1/3.

This will run 5-6 times for reasonable n (not 0) (the number is not important and depends on how do you calculate /)

Salvador Dali
  • 214,103
  • 147
  • 703
  • 753
1

The inner loop increments by a multiple of n, not by 1, so its runtime is bounded by a constant (6?). So the total number of steps is bounded by a constant multiple of n (namely 6n).

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084