65.9k views
1 vote
What would be the running time for the code below

int sum = 1;
for (int i = 1; i <= n; i++)
for (int j = i; j <= n; j++)
for (int k = i; k <= j; k++)
sum++;

User Jomaora
by
8.3k points

1 Answer

6 votes

Final answer:

The running time for the given code is approximately O(n^3) due to its three nested loops.

Step-by-step explanation:

The running time for the given code can be determined by analyzing the nested for loops. The outer loop runs n times, the second loop runs n - i + 1 times, and the innermost loop runs j - i + 1 times. Summing up all the iterations, the total number of iterations will be:

  1. (n - 1) + (n - 2) + ... + 1 = n * (n - 1) / 2
  2. (n - 2) + (n - 3) + ... + 1 = (n - 1) * (n - 2) / 2
  3. ...
  4. 1

As a result, the running time for the code is approximately O(n^3) because it has three nested loops.

User Viswesn
by
7.8k points

No related questions found

Welcome to QAmmunity.org, where you can ask questions and receive answers from other members of our community.

9.4m questions

12.2m answers

Categories