Knowee
Questions
Features
Study Tools

What is the time complexity of this function / algorithm?void f(int n){ int i; int j; for (i = 0; i < n; i++) { if (i % 2 == 0) { for (j = 1; j < n; j = j * 2) { printf("[%d] [%d]\n", i, j); } } else { for (j = 0; j < n; j = j + 2) { printf("[%d] [%d]\n", i, j); } } }}O(n)O(1)O(log(n))O(nlog(n))O(2^n)O(n!)O(n^2)

Question

What is the time complexity of this function / algorithm?void f(int n){ int i; int j; for (i = 0; i < n; i++) { if (i % 2 == 0) { for (j = 1; j < n; j = j * 2) { printf("[%d] [%d]\n", i, j); } } else { for (j = 0; j < n; j = j + 2) { printf("[%d] [%d]\n", i, j); } } }}O(n)O(1)O(log(n))O(nlog(n))O(2^n)O(n!)O(n^2)

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

Solution

The time complexity of the given function can be determined by analyzing the loops in the function.

  1. The outer loop runs 'n' times as it is directly dependent on 'n'. So, it has a time complexity of O(n).

  2. The inner loop has two different cases:

    • When 'i' is even, the loop runs log(n) times because 'j' is multiplied by 2 in each iteration. So, the time complexity is O(log(n)).
    • When 'i' is odd, the loop runs n/2 times because 'j' is incremented by 2 in each iteration. In terms of time complexity, we consider the highest power of 'n', so it is O(n).
  3. Since these loops are nested, we multiply their time complexities for the total time complexity. However, we only consider the highest time complexity for each case. So, the total time complexity is O(n) * max(O(log(n)), O(n)) = O(n^2).

So, the time complexity of the function is O(n^2).

This problem has been solved

Similar Questions

What is the time complexity of this function / algorithm?void f(int n){ int i; for (i = 0; i < n; i++) { printf("[%d]\n", i); }}O(n)O(1)O(log(n))O(nlog(n))O(2^n)O(n!)O(n^2)

What is the time complexity of this function / algorithm?void f(unsigned int n){ int i; for (i = 1; i < n; i = i * 2) { printf("[%d]\n", i); }}

What is the time complexity of this function / algorithm?void f(int n){ printf("n = %d\n", n);}

What is the time complexity of this function / algorithm?void f(int n){ int i; for (i = 0; i < n; i += 98) { printf("[%d]\n", i); }}

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; }}

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.