Hello,
In the solution breakdown of Solution Review: Big O of a Nested Loop with Subtraction , it says that var >= 1;
is executed n/3 + 1
times in the outer for-loop:
int n = 10;
...
for (int var = n; var >= 1; var = var - 3) {
...
}
but I don’t see how that is calculated.
If I use n = 10
then var
would be compared like this:
- First iteration:
10 >= 1
- Second iteration:
7 >= 1
- Third iteration:
4 >= 1
- Fourth iteration:
1 >= 1
- Fifth iteration:
-2 >= 1
If it’s actually n/3 + 1
as the solution suggests, for n = 10
it would be 10/3 + 1 ~ 4
which is not correct since the comparsion was made five times, the fifth time is to exit the loop.
So I think the number of executions for var >= 1
is n/3 + 2
, am I wrong? if so, can somebody explain me how n/3 + 1
was calculated?
Thank you