Knowee
Questions
Features
Study Tools

Q2(b) What will be the time complexity of the following? Give proper explanation. for (int j = 4; j<n; j=j+2) { val = 0; for (int i = 0; i<j; ++i) { val = val + i* j; for (int k = 0; k < n; ++k) val++; } }

Question

Q2(b) What will be the time complexity of the following? Give proper explanation. for (int j = 4; j<n; j=j+2) { val = 0; for (int i = 0; i<j; ++i) { val = val + i* j; for (int k = 0; k < n; ++k) val++; } }

🧐 Not the exact question you are looking for?Go ask a question

Solution

The time complexity of the given code can be calculated as follows:

  1. The outermost loop runs from 4 to n with an increment of 2 each time. So, it runs approximately n/2 times. We can consider this as O(n) for simplicity.

  2. The middle loop runs 'j' times, where 'j' is less than 'n'. So, in the worst case, it runs 'n' times. Hence, the time complexity of the middle loop is O(n).

  3. The innermost loop runs 'n' times. So, its time complexity is O(n).

Since these loops are nested, we multiply the time complexities of each loop to get the overall time complexity. Therefore, the time complexity of the given code is O(n^3).

This is because the outer loop runs in O(n) time, the middle loop runs in O(n) time for each iteration of the outer loop, and the innermost loop runs in O(n) time for each iteration of the middle loop. When you multiply these together, you get O(n^3).

Please note that this is the worst-case time complexity. The actual time complexity could be less depending on the values of 'n' and 'j'.

This problem has been solved

Similar Questions

What is the time complexity of the following code :int i, j, k = 0;for (i = n/2; i <= n; i++) { for (j = 2; j <= n; j = j * 2) { k = k + n/2; }}

What is the time complexity of the following code : int a = 0; for (i = 0; i < N; i++) { for (j = N; j > i; j--) { a = a + i + j; } }

What is the time complexity of the following code? for(int i = 0; i < n; i++) { for(int j = 0; j < i; j++) { System.out.println(i * j); } } a. O(n) b. O(2^n) c. O(n^2) d. O(n log n)

What is the time, space complexity of following code :int a = 0, b = 0; for (i = 0; i < N; i++) { for (j = 0; j < N; j++) { a = a + j; } } for (k = 0; k < N; k++) { b = b + k; }

What will be the time complexity of the following code?int fun(int n){ int count = 0; for (int i = n; i > 0; i /= 2){ for (int j = 0; j < i; j++){ count += 1;| } }return count;

1/3

Upgrade your grade with Knowee

Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.