>That would mean the answer would be b.
No, the answer is d. There's no question about it since the inner loop you posted relies on N, not the value of the outer loop counter.
Now, if you're talking about counter2 being set to counter1 and using it as N, the answer would still be d because Big-O is an upper bound. For example:
for ( int i = 0; i < 10; i++ ) {
for ( int j = i; j >= 0; j-- )
;
}
When i is 9 then j runs the full length of the outer loop, which is O(N). Since the outer loop is O(N), that gives you O(N^2). If you use O(N) as the upper bound, you've basically lied about your algorithm even though when i is 0, the inner loop isn't ten iterations. Even if it's for one iteration of the outer loop, the upper bound of the algorithm is O(N^2).
If you're really interested in being precise, you can work out a detailed analysis based on the increasing inner loop iterations. But that's not always worth it, and certainly not for this question.
>Same thing with this problem.
This is another form of the example I just gave.
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
If you're really interested in being precise, you can work out a detailed analysis based on the increasing inner loop iterations. But that's not always worth it, and certainly not for this question.
To give an example of what Narue's talking about, it's not too hard to see that the total number of times you output the value count1+count2 will be N the first time through, N - 1 the second time, N - 2, the third time, and so on.
Then the total number of times you print a number will be N + (N - 1) + (N - 2) + ... + 3 + 2 + 1. This is known to equal (N^2 + N) / 2. Then your running time is O(N^2), since N^2 /2 becomes the dominating term when N gets really large.
Once you've done this (or seen it) once or twice, it becomes obvious, and going through motions like these are a waste of time, anytime you come across some pair of for loops with a similar structure.
Rashakil Fol
Super Senior Demiposter
2,658 posts since Jun 2005
Reputation Points: 1,135
Solved Threads: 177