Lisa H.

asked • 10/15/21

Why is the answer O(N^2) for this big-o question?

For this question:


Approximate the runtime of the following code fragment, in terms of n: Write your answer in a format such as "O(N^2)" or "O(N log N)".

int sum = 0;

for (int i = 1; i <= n; i++) {

for (int j = 1; j <= i; j += 2) {

sum += 4;

}

}

for (int k = -50; k <= -1; k++) {

sum--;

}


Why is the answer O(N^2)? For the first for-loop, the big-o is O(N). For the next for-loop, the big-o should be O(log N), right? Because it increments by 2 each time. For the last for-loop, the big-o is O(49), which is reduced to O(1). So then, shouldn't the big-o overall be O(N) because O(N) is the largest? Please explain this to me.

1 Expert Answer

By:

Still looking for help? Get the right answer, fast.

Ask a question for free

Get a free answer to a quick problem.
Most questions answered within 4 hours.

OR

Find an Online Tutor Now

Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.