Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 7

Q1).

Find the Answer:


Q2). Find the Answer:

Q3). Find the Answer:

printf("The desired divisor is m = %d\n",m); }

Q4). Find the Answer: Time Complexity Examples


Example 1 int fun(int n) Time Complexity:
{
int m = 0;
for (int i = 0; i<n; i++)
m += 1;
return m;
}

Example 2 int fun(int n) Time Complexity:


{
int i=0, j=0, m = 0;
for (i = 0; i<n; i++)
for (j = 0; j<n; j++)
m += 1;
return m;
}
Example 3 int fun(int n) Time Complexity:
{
int i=0, j=0, m = 0;
for (i = 0; i<n; i++)
for (j = 0; j<i; j++)
m += 1;
return m;
}

Example 4 int fun(int n) Each time problem space is


{ divided into half.
int i = 0, m = 0; Time Complexity:
i = 1;
while (i < n) {
m += 1;
i = i * 2;
}
return m;
}

Example 5 int fun(int n) Same as above each time


{ problem space is divided into
int i = 0, m = 0; half.
i = n; Time Complexity:
while (i > 0) {
m += 1;
i = i / 2;
}
return m;
}

Example 6 int fun(int n) Outer loop will run for n


{ number of iterations. In each
int i = 0, j = 0, k = 0, m = 0; iteration of the outer loop,
i = n; inner loop will run for n
for (i = 0; i<n; i++) iterations of their own. Final
for (j = 0; j<n; j++) complexity will be n*n*n
for (k = 0; k<n; k++) Time Complexity:
m += 1;
return m;
}

Example 7 int fun(int n) These two groups of for loop


{ are in consecutive so their
int i = 0, j = 0, k = 0, m = 0; complexity will add up to
i = n; form the final
for (i = 0; i<n; i++) complexity of the program.
for (j = 0; j<n; j++) Time Complexity:
m += 1;
for (i = 0; i<n; i++)
for (k = 0; k<n; k++)
m += 1;
return m;
}

Example 8 int fun(int n) Time Complexity:


{
int i = 0, j = 0, m = 0;
for (i = 0; i<n; i++)
for (j = 0; j< sqrt(n); j++)
m += 1;
return m;
}

Example 9 int fun(int n) Each time problem space is


{ divided into half.
int i = 0, j = 0, m = 0; Time Complexity:
for (i = n; i > 0; i /= 2)
for (j = 0; j < i; j++)
m += 1;
return m;
}

Example 10 int fun(int n) O(N+(N-1)+(N-2)+...) =


{ O(N(N+1)/2) // arithmetic
int i = 0, j = 0, m = 0; progression.
for (i = 0; i < n; i++) Time Complexity:
for (j = i; j > 0; j--)
m += 1;
return m;
}

Example 11 int fun(int n) Time Complexity:


{
int i = 0, j = 0, k = 0, m = 0;
for (i = 0; i<n; i++)
for (j = i; j<n; j++)
for (k = j+1; k<n; k++)
m += 1;
return m;
}

Example 12 int fun(int n) Think carefully once again


{ before finding a solution, j
int i = 0, j = 0, m = 0; value is not reset at each
for (i = 0; i<n; i++) iteration.
for (; j<n; j++) Time Complexity:
m += 1;
return m;
}
Example 13 int fun(int n) The inner loop will run for 1,
{ 2, 4, 8,… n times in
int i = 1, j = 0, m = 0; successive iteration of the
for (i = 1; i<=n; i *= 2) outer loop.
for (j = 0; j<=i; j++) Time Complexity: T(n) =
m += 1; O(1+ 2+ 4+ ….+n/2+n)
return m;
}

You might also like